Example usage for org.apache.solr.client.solrj.request CoreAdminRequest setCoreName

List of usage examples for org.apache.solr.client.solrj.request CoreAdminRequest setCoreName

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.request CoreAdminRequest setCoreName.

Prototype

public void setCoreName(String coreName) 

Source Link

Usage

From source file:com.datasalt.utils.viewbuilder.SolrAdminCoreUtils.java

License:Apache License

public static NamedList<Object> hotSwapCores(SolrServer adminServer, String coreName, String otherCoreName)
        throws SolrServerException, IOException {

    CoreAdminRequest aReq = new CoreAdminRequest();
    aReq.setAction(CoreAdminAction.SWAP);
    aReq.setCoreName(coreName);
    aReq.setOtherCoreName(otherCoreName);
    return adminServer.request(aReq);
}

From source file:com.github.fengtan.sophie.toolbars.CoresToolbar.java

License:Open Source License

/**
 * Populate toolbar with buttons.//from  w  w  w .  ja  va  2s  .co  m
 * 
 * @param composite
 *            Parent composite.
 */
private void initToolbar(final Composite composite) {
    Display display = composite.getDisplay();
    ClassLoader loader = getClass().getClassLoader();

    // Instantiate toolbar.
    ToolBar toolBar = new ToolBar(composite, SWT.BORDER);

    // Instantiate images.
    imgRefresh = new Image(display, loader.getResourceAsStream("toolbar/refresh.png"));
    imgAdd = new Image(display, loader.getResourceAsStream("toolbar/add.png"));
    imgDelete = new Image(display, loader.getResourceAsStream("toolbar/delete.png"));
    imgRename = new Image(display, loader.getResourceAsStream("toolbar/rename.png"));
    imgSwap = new Image(display, loader.getResourceAsStream("toolbar/swap.png"));
    imgReload = new Image(display, loader.getResourceAsStream("toolbar/restore.png"));
    imgReloadAll = new Image(display, loader.getResourceAsStream("toolbar/restore.png"));

    // Instantiate buttons.
    itemRefresh = new ToolItem(toolBar, SWT.PUSH);
    itemRefresh.setImage(imgRefresh);
    itemRefresh.setText("Refresh");
    itemRefresh.setToolTipText("Refresh list of cores");
    itemRefresh.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            try {
                table.refresh();
            } catch (SophieException e) {
                ExceptionDialog.open(composite.getShell(),
                        new SophieException("Unable to refresh list of cores", e));
            }
        }
    });

    new ToolItem(toolBar, SWT.SEPARATOR);

    itemAdd = new ToolItem(toolBar, SWT.PUSH);
    itemAdd.setImage(imgAdd);
    itemAdd.setText("Add");
    itemAdd.setToolTipText("Add new core");
    itemAdd.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            String[] labels = new String[] { "Name:", "Instance Directory:", "Config file:", "Schema file:",
                    "Data Directory:", "Transaction log directory:" };
            String[] defaultValues = new String[] { "collectionX", "/path/to/solr/collectionX",
                    "solrconfig.xml", "schema.xml", "/path/to/solr/collectionX/data",
                    "/path/to/solr/collectionX/tlog" };
            MultipleInputDialog dialog = new MultipleInputDialog(composite.getShell(), "Add new core", labels,
                    defaultValues);
            dialog.open();
            if (dialog.getReturnCode() != IDialogConstants.OK_ID) {
                return;
            }
            try {
                CoreAdminRequest.createCore(dialog.getValue(0), dialog.getValue(1), Sophie.client,
                        dialog.getValue(2), dialog.getValue(3), dialog.getValue(4), dialog.getValue(5));
                table.refresh();
            } catch (SolrServerException | IOException | SolrException | SophieException e) {
                ExceptionDialog.open(composite.getShell(),
                        new SophieException("Unable to add new core \"" + dialog.getValue(0) + "\"", e));
            }
        }
    });

    itemDelete = new ToolItem(toolBar, SWT.PUSH);
    itemDelete.setImage(imgDelete);
    itemDelete.setText("Delete");
    itemDelete.setToolTipText("Delete core");
    itemDelete.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            String coreName = table.getSelectedCore();
            MessageBox messageBox = new MessageBox(composite.getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
            messageBox.setText("Delete core");
            messageBox.setMessage("Do you really want to delete this core (\"" + coreName + "\") ?");
            int response = messageBox.open();
            if (response == SWT.YES) {
                try {
                    CoreAdminRequest.unloadCore(coreName, Sophie.client);
                    table.refresh();
                } catch (SolrServerException | IOException | SolrException | SophieException e) {
                    ExceptionDialog.open(composite.getShell(),
                            new SophieException("Unable to delete core \"" + coreName + "\"", e));
                }
            }
        }
    });
    itemDelete.setEnabled(false);

    itemRename = new ToolItem(toolBar, SWT.PUSH);
    itemRename.setImage(imgRename);
    itemRename.setText("Rename");
    itemRename.setToolTipText("Rename core");
    itemRename.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            String oldCoreName = table.getSelectedCore();
            InputDialog newCoreName = new InputDialog(composite.getShell(), "Rename core",
                    "New name (\"" + oldCoreName + "\"):", oldCoreName, null);
            newCoreName.open();
            if (newCoreName.getReturnCode() != IDialogConstants.OK_ID) {
                return;
            }
            try {
                CoreAdminRequest.renameCore(oldCoreName, newCoreName.getValue(), Sophie.client);
                table.refresh();
            } catch (SolrServerException | IOException | SolrException | SophieException e) {
                ExceptionDialog.open(composite.getShell(), new SophieException(
                        "Unable to rename core \"" + oldCoreName + "\" into \"" + newCoreName + "\"", e));
            }
        }
    });
    itemRename.setEnabled(false);

    new ToolItem(toolBar, SWT.SEPARATOR);

    itemSwap = new ToolItem(toolBar, SWT.PUSH);
    itemSwap.setImage(imgSwap);
    itemSwap.setText("Swap");
    itemSwap.setToolTipText("Swap cores");
    itemSwap.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            String coreName = table.getSelectedCore();
            Map<String, NamedList<Object>> cores;
            try {
                cores = SolrUtils.getCores();
            } catch (SophieException e) {
                Sophie.log.error("Unable to suggest list of cores", e);
                cores = Collections.emptyMap();
            }
            Object[] coreObjects = cores.keySet().toArray();
            String[] coreStrings = Arrays.copyOf(coreObjects, coreObjects.length, String[].class);
            CComboDialog dialog = new CComboDialog(composite.getShell(), "Swap cores",
                    "Swap core \"" + coreName + "\" with:", coreStrings, null);
            dialog.open();
            if (dialog.getReturnCode() != IDialogConstants.OK_ID) {
                return;
            }
            CoreAdminRequest request = new CoreAdminRequest();
            request.setCoreName(coreName);
            request.setOtherCoreName(dialog.getValue());
            request.setAction(CoreAdminAction.SWAP);
            try {
                request.process(Sophie.client);
                table.refresh();
            } catch (SolrServerException | IOException | SolrException | SophieException e) {
                ExceptionDialog.open(composite.getShell(), new SophieException(
                        "Unable to swap cores \"" + coreName + "\" and \"" + dialog.getValue() + "\"", e));
            }
        }
    });
    itemSwap.setEnabled(false);

    itemReload = new ToolItem(toolBar, SWT.PUSH);
    itemReload.setImage(imgReload);
    itemReload.setText("Reload");
    itemReload.setToolTipText(
            "Reload core - this will reload any configuration changes you may have made to solrconfig.xml or schema.xml");
    itemReload.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            String coreName = table.getSelectedCore();
            try {
                CoreAdminRequest.reloadCore(coreName, Sophie.client);
                table.refresh();
            } catch (SolrServerException | IOException | SolrException | SophieException e) {
                ExceptionDialog.open(composite.getShell(),
                        new SophieException("Unable to reload core \"" + coreName + "\"", e));
            }
        }
    });
    itemReload.setEnabled(false);

    itemReloadAll = new ToolItem(toolBar, SWT.PUSH);
    itemReloadAll.setImage(imgReloadAll);
    itemReloadAll.setText("Reload all");
    itemReloadAll.setToolTipText("Reload all cores");
    itemReloadAll.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            try {
                for (String coreName : SolrUtils.getCores().keySet()) {
                    CoreAdminRequest.reloadCore(coreName, Sophie.client);
                }
                table.refresh();
            } catch (SolrServerException | IOException | SolrException | SophieException e) {
                ExceptionDialog.open(composite.getShell(),
                        new SophieException("Unable to reload all cores", e));
            }
        }
    });

    toolBar.pack();
}

From source file:org.broadleafcommerce.core.search.service.solr.SolrHelperServiceImpl.java

License:Apache License

/**
 * This should only ever be called when using the Solr reindex service to do a full reindex. 
 *//*from  ww  w .ja va  2s.  c  o  m*/
@Override
public synchronized void swapActiveCores() throws ServiceException {
    if (SolrContext.isSolrCloudMode()) {
        CloudSolrServer primary = (CloudSolrServer) SolrContext.getServer();
        CloudSolrServer reindex = (CloudSolrServer) SolrContext.getReindexServer();
        try {
            primary.connect();
            Aliases aliases = primary.getZkStateReader().getAliases();
            Map<String, String> aliasCollectionMap = aliases.getCollectionAliasMap();
            if (aliasCollectionMap == null || !aliasCollectionMap.containsKey(primary.getDefaultCollection())
                    || !aliasCollectionMap.containsKey(reindex.getDefaultCollection())) {
                throw new IllegalStateException("Could not determine the PRIMARY or REINDEX "
                        + "collection or collections from the Solr aliases.");
            }

            String primaryCollectionName = aliasCollectionMap.get(primary.getDefaultCollection());
            //Do this just in case primary is aliased to more than one collection
            primaryCollectionName = primaryCollectionName.split(",")[0];

            String reindexCollectionName = aliasCollectionMap.get(reindex.getDefaultCollection());
            //Do this just in case primary is aliased to more than one collection
            reindexCollectionName = reindexCollectionName.split(",")[0];

            //Essentially "swap cores" here by reassigning the aliases
            CollectionAdminRequest.createAlias(primary.getDefaultCollection(), reindexCollectionName, primary);
            CollectionAdminRequest.createAlias(reindex.getDefaultCollection(), primaryCollectionName, primary);
        } catch (Exception e) {
            LOG.error("An exception occured swapping cores.", e);
            throw new ServiceException("Unable to swap SolrCloud collections after a full reindex.", e);
        }
    } else {
        if (SolrContext.isSingleCoreMode()) {
            LOG.debug("In single core mode. There are no cores to swap.");
        } else {
            LOG.debug("Swapping active cores");

            CoreAdminRequest car = new CoreAdminRequest();
            car.setCoreName(SolrContext.PRIMARY);
            car.setOtherCoreName(SolrContext.REINDEX);
            car.setAction(CoreAdminAction.SWAP);

            try {
                SolrContext.getAdminServer().request(car);
            } catch (Exception e) {
                LOG.error(e);
                throw new ServiceException("Unable to swap cores", e);
            }
        }
    }
}

From source file:org.craftercms.search.service.impl.SolrAdminService.java

License:Open Source License

@Override
public Map<String, Object> getIndexInfo(String id) throws SearchException {
    CoreAdminRequest request = new CoreAdminRequest();
    request.setCoreName(id);
    request.setIndexInfoNeeded(true);// w w  w  .  j a  va 2 s.c  o m
    request.setAction(CoreAdminParams.CoreAdminAction.STATUS);

    try {
        CoreAdminResponse response = request.process(solrClient);
        Map<String, Object> info = null;

        if (response != null) {
            NamedList<Object> status = response.getCoreStatus(id);
            if (status != null) {
                info = status.asShallowMap();
            }
        }

        if (MapUtils.isNotEmpty(info)) {
            return info;
        } else {
            throw new IndexNotFoundException("Index '" + id + "' not ");
        }
    } catch (SolrServerException | IOException e) {
        throw new SearchException(id, "Failed to get core info", e);
    }
}

From source file:org.dspace.util.SolrImportExport.java

License:BSD License

/**
 * Reindexes the specified core//  w  ww. j  a va  2 s.c  o m
 *
 * @param indexName the name of the core to reindex
 * @param exportDirName the name of the directory to use for export. If this directory doesn't exist, it will be created.
 * @param keepExport whether to keep the contents of the exportDir after the reindex. If keepExport is false and the
 *                      export directory was created by this method, the export directory will be deleted at the end of the reimport.
 */
private static void reindex(String indexName, String exportDirName, boolean keepExport)
        throws IOException, SolrServerException, SolrImportExportException {
    String tempIndexName = indexName + "-temp";

    String origSolrUrl = makeSolrUrl(indexName);
    String baseSolrUrl = StringUtils.substringBeforeLast(origSolrUrl, "/"); // need to get non-core solr URL
    String tempSolrUrl = baseSolrUrl + "/" + tempIndexName;

    String solrInstanceDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr"
            + File.separator + indexName;
    // the [dspace]/solr/[indexName]/conf directory needs to be available on the local machine for this to work
    // -- we need access to the schema.xml and solrconfig.xml file, plus files referenced from there
    // if this directory can't be found, output an error message and skip this index
    File solrInstance = new File(solrInstanceDir);
    if (!solrInstance.exists() || !solrInstance.canRead() || !solrInstance.isDirectory()) {
        throw new SolrImportExportException("Directory " + solrInstanceDir
                + "/conf/ doesn't exist or isn't readable."
                + " The reindexing process requires the Solr configuration directory for this index to be present on the local machine"
                + " even if Solr is running on a different host. Not reindexing index " + indexName);
    }

    String timeField = makeTimeField(indexName);

    // Ensure the export directory exists and is writable
    File exportDir = new File(exportDirName);
    boolean createdExportDir = exportDir.mkdirs();
    if (!createdExportDir && !exportDir.exists()) {
        throw new SolrImportExportException("Could not create export directory " + exportDirName);
    }
    if (!exportDir.canWrite()) {
        throw new SolrImportExportException("Can't write to export directory " + exportDirName);
    }

    try {
        HttpSolrServer adminSolr = new HttpSolrServer(baseSolrUrl);

        // try to find out size of core and compare with free space in export directory
        CoreAdminResponse status = CoreAdminRequest.getStatus(indexName, adminSolr);
        Object coreSizeObj = status.getCoreStatus(indexName).get("sizeInBytes");
        long coreSize = coreSizeObj != null ? Long.valueOf(coreSizeObj.toString()) : -1;
        long usableExportSpace = exportDir.getUsableSpace();
        if (coreSize >= 0 && usableExportSpace < coreSize) {
            System.err.println("Not enough space in export directory " + exportDirName
                    + "; need at least as much space as the index ("
                    + FileUtils.byteCountToDisplaySize(coreSize)
                    + ") but usable space in export directory is only "
                    + FileUtils.byteCountToDisplaySize(usableExportSpace)
                    + ". Not continuing with reindex, please use the " + DIRECTORY_OPTION
                    + " option to specify an alternative export directy with sufficient space.");
            return;
        }

        // Create a temp directory to store temporary core data
        File tempDataDir = new File(ConfigurationManager.getProperty("dspace.dir") + File.separator + "temp"
                + File.separator + "solr-data");
        boolean createdTempDataDir = tempDataDir.mkdirs();
        if (!createdTempDataDir && !tempDataDir.exists()) {
            throw new SolrImportExportException(
                    "Could not create temporary data directory " + tempDataDir.getCanonicalPath());
        }
        if (!tempDataDir.canWrite()) {
            throw new SolrImportExportException(
                    "Can't write to temporary data directory " + tempDataDir.getCanonicalPath());
        }

        try {
            // create a temporary core to hold documents coming in during the reindex
            CoreAdminRequest.Create createRequest = new CoreAdminRequest.Create();
            createRequest.setInstanceDir(solrInstanceDir);
            createRequest.setDataDir(tempDataDir.getCanonicalPath());
            createRequest.setCoreName(tempIndexName);

            createRequest.process(adminSolr).getStatus();
        } catch (SolrServerException e) {
            // try to continue -- it may just be that the core already existed from a previous, failed attempt
            System.err.println("Caught exception when trying to create temporary core: " + e.getMessage()
                    + "; trying to recover.");
            e.printStackTrace(System.err);
        }

        // swap actual core with temporary one
        CoreAdminRequest swapRequest = new CoreAdminRequest();
        swapRequest.setCoreName(indexName);
        swapRequest.setOtherCoreName(tempIndexName);
        swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP);
        swapRequest.process(adminSolr);

        try {
            // export from the actual core (from temp core name, actual data dir)
            exportIndex(indexName, exportDir, tempSolrUrl, timeField);

            // clear actual core (temp core name, clearing actual data dir) & import
            importIndex(indexName, exportDir, tempSolrUrl, true, true);
        } catch (Exception e) {
            // we ran into some problems with the export/import -- keep going to try and restore the solr cores
            System.err.println("Encountered problem during reindex: " + e.getMessage()
                    + ", will attempt to restore Solr cores");
            e.printStackTrace(System.err);
        }

        // commit changes
        HttpSolrServer origSolr = new HttpSolrServer(origSolrUrl);
        origSolr.commit();

        // swap back (statistics now going to actual core name in actual data dir)
        swapRequest = new CoreAdminRequest();
        swapRequest.setCoreName(tempIndexName);
        swapRequest.setOtherCoreName(indexName);
        swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP);
        swapRequest.process(adminSolr);

        // export all docs from now-temp core into export directory -- this won't cause name collisions with the actual export
        // because the core name for the temporary export has -temp in it while the actual core doesn't
        exportIndex(tempIndexName, exportDir, tempSolrUrl, timeField);
        // ...and import them into the now-again-actual core *without* clearing
        importIndex(tempIndexName, exportDir, origSolrUrl, false, true);

        // commit changes
        origSolr.commit();

        // unload now-temp core (temp core name)
        CoreAdminRequest.unloadCore(tempIndexName, false, false, adminSolr);

        // clean up temporary data dir if this method created it
        if (createdTempDataDir && tempDataDir.exists()) {
            FileUtils.deleteDirectory(tempDataDir);
        }
    } finally {
        // clean up export dir if appropriate
        if (!keepExport && createdExportDir && exportDir.exists()) {
            FileUtils.deleteDirectory(exportDir);
        }
    }
}

From source file:org.opencommercesearch.CloudSearchServer.java

License:Apache License

/**
 * Reloads the core/*from w ww.  jav  a  2s. com*/
 *
 * @param collectionName
 *            the cored to be reloaded
 *
 * @throws SearchServerException
 *          if an error occurs while reloading the core
 *
 */
public void reloadCollection(String collectionName, Locale locale) throws SearchServerException {
    CoreAdminRequest adminRequest = new CoreAdminRequest();
    adminRequest.setCoreName(collectionName);
    adminRequest.setAction(CoreAdminAction.RELOAD);

    CloudSolrServer server = getSolrServer(collectionName, locale);
    ZkStateReader zkStateReader = server.getZkStateReader();
    if (zkStateReader == null) {
        //if the zkStateReader is null it means we haven't connect to this collection
        server.connect();
        zkStateReader = server.getZkStateReader();
    }

    ClusterState clusterState = zkStateReader.getClusterState();
    Set<String> liveNodes = clusterState.getLiveNodes();

    if (liveNodes == null || liveNodes.size() == 0) {
        if (isLoggingInfo()) {
            logInfo("No live nodes found, 0 cores were reloaded");
        }
        return;
    }

    Map<String, Slice> slices = clusterState.getSlicesMap(collectionName);
    if (slices.size() == 0) {
        if (isLoggingInfo()) {
            logInfo("No slices found, 0 cores were reloaded");
        }
    }

    for (Slice slice : slices.values()) {
        for (ZkNodeProps nodeProps : slice.getReplicas()) {
            ZkCoreNodeProps coreNodeProps = new ZkCoreNodeProps(nodeProps);
            String node = coreNodeProps.getNodeName();
            if (!liveNodes.contains(coreNodeProps.getNodeName())
                    || !coreNodeProps.getState().equals(ZkStateReader.ACTIVE)) {
                if (isLoggingInfo()) {
                    logInfo("Node " + node + " is not live, unable to reload core " + collectionName);
                }
                continue;
            }

            if (isLoggingInfo()) {
                logInfo("Reloading core " + collectionName + " on " + node);
            }
            HttpClient httpClient = server.getLbServer().getHttpClient();
            HttpSolrServer nodeServer = new HttpSolrServer(coreNodeProps.getBaseUrl(), httpClient,
                    getResponseParser());
            try {
                CoreAdminResponse adminResponse = adminRequest.process(nodeServer);
                if (isLoggingInfo()) {
                    logInfo("Reladed core " + collectionName + ", current status is "
                            + adminResponse.getCoreStatus());
                }
            } catch (SolrServerException ex) {
                if (ex.getCause() instanceof SocketTimeoutException) {
                    //if we experience a socket timeout out don't kill the entire process. Try to reload the other nodes
                    if (isLoggingError()) {
                        logError("Reloading core failed due to socket timeout for node [" + node
                                + "] and collection [" + collectionName + "]");
                    }
                } else {
                    throw create(CORE_RELOAD_EXCEPTION, ex);
                }
            } catch (IOException ex) {
                throw create(CORE_RELOAD_EXCEPTION, ex);
            }
        }
    }
}

From source file:org.sparkcommerce.core.search.service.solr.SolrHelperServiceImpl.java

License:Apache License

@Override
public void swapActiveCores() throws ServiceException {
    if (SolrContext.isSingleCoreMode()) {
        LOG.debug("In single core mode. There are no cores to swap.");
    } else {//www .j ava 2 s .  c  o m
        LOG.debug("Swapping active cores");

        CoreAdminRequest car = new CoreAdminRequest();
        car.setCoreName(SolrContext.PRIMARY);
        car.setOtherCoreName(SolrContext.REINDEX);
        car.setAction(CoreAdminAction.SWAP);

        try {
            SolrContext.getAdminServer().request(car);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException("Unable to swap cores", e);
        }
    }
}