List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast
public static String substringBeforeLast(String str, String separator)
Gets the substring before the last occurrence of a separator.
From source file:org.dspace.discovery.SolrServiceImpl.java
protected String transformFacetField(DiscoverFacetField facetFieldConfig, String field, boolean removePostfix) { if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) { if (removePostfix) { return field.substring(0, field.lastIndexOf("_filter")); } else {// w w w . j a v a 2 s. c o m return field + "_filter"; } } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) { if (removePostfix) { return field.substring(0, field.lastIndexOf(".year")); } else { return field + ".year"; } } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AC)) { if (removePostfix) { return field.substring(0, field.lastIndexOf("_ac")); } else { return field + "_ac"; } } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) { if (removePostfix) { return StringUtils.substringBeforeLast(field, "_tax_"); } else { //Only display top level filters ! return field + "_tax_0_filter"; } } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AUTHORITY)) { if (removePostfix) { return field.substring(0, field.lastIndexOf("_acid")); } else { return field + "_acid"; } } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_STANDARD)) { return field; } else { return field; } }
From source file:org.dspace.util.SolrImportExport.java
/** * Reindexes the specified core/* www . j av a 2 s .co 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. * @param overwrite allow export files to be overwritten during re-index */ private static void reindex(String indexName, String exportDirName, boolean keepExport, boolean overwrite) 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; //The configuration details for the statistics shards reside within the "statistics" folder String instanceIndexName = indexName.startsWith("statistics-") ? "statistics" : indexName; String solrInstanceDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr" + File.separator + instanceIndexName; // 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, overwrite); // clear actual core (temp core name, clearing actual data dir) & import importIndex(indexName, exportDir, tempSolrUrl, 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, overwrite); // ...and import them into the now-again-actual core *without* clearing importIndex(tempIndexName, exportDir, origSolrUrl, false); // 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.ebayopensource.turmeric.eclipse.buildsystem.utils.ProjectPropertiesFileUtil.java
/** * Creates the interface project properties file. The name of the file is * "service_intf_project.properties". This file has information like source * type of the project, package to name space mapping etc. * * @param soaIntfProject the soa intf project * @param monitor the monitor/*from www . ja v a 2 s . co m*/ * @return the i file * @throws IOException Signals that an I/O exception has occurred. * @throws CoreException the core exception */ public static IFile createPropsFile(SOAIntfProject soaIntfProject, IProgressMonitor monitor) throws IOException, CoreException { IFile file = soaIntfProject.getEclipseMetadata().getProject() .getFile(SOAProjectConstants.PROPS_FILE_SERVICE_INTERFACE); OutputStream output = null; try { output = new ByteArrayOutputStream(); final Properties properties = new Properties(); final SOAIntfMetadata metadata = soaIntfProject.getMetadata(); addServiceMetadataProperties(properties, metadata); if (metadata.getServiceNonXSDProtocols() == null) { boolean protoBufCreated = ProjectProtoBufFileUtil.createServiceProtoBufFile(soaIntfProject, metadata.getServiceLocation()); if (protoBufCreated == true) { properties.setProperty(SOAProjectConstants.PROP_KEY_NON_XSD_FORMATS, SOAProjectConstants.SVC_PROTOCOL_BUF); } } if (SOAProjectConstants.InterfaceSourceType.WSDL.equals(metadata.getSourceType()) || SOAProjectConstants.InterfaceWsdlSourceType.EXISTIING.equals(metadata.getWsdlSourceType())) { properties.setProperty(SOAProjectConstants.PROPS_INTF_SOURCE_TYPE, SOAProjectConstants.PROPS_INTF_SOURCE_TYPE_WSDL); if (metadata.getNamespaceToPackageMappings().isEmpty() == false) { final Collection<String> data = new ArrayList<String>(); for (final String namespace : metadata.getNamespaceToPackageMappings().keySet()) { final String pakcage = metadata.getNamespaceToPackageMappings().get(namespace); data.add(namespace + SOAProjectConstants.DELIMITER_PIPE + pakcage); } final String ns2pkg = StringUtils.join(data, SOAProjectConstants.DELIMITER_COMMA); properties.setProperty(SOAProjectConstants.PROPS_KEY_NAMESPACE_TO_PACKAGE, ns2pkg); } } else { properties.setProperty(SOAProjectConstants.PROPS_INTF_SOURCE_TYPE, SOAProjectConstants.PROPS_INTF_SOURCE_TYPE_JAVA); } if (!metadata.getTypeFolding() && StringUtils.isNotBlank(metadata.getTypeNamespace())) { properties.setProperty(SOAProjectConstants.PROPS_KEY_TYPE_NAMESPACE, metadata.getTypeNamespace()); } if (StringUtils.isNotBlank(metadata.getServiceDomainName())) { properties.setProperty(SOAProjectConstants.PROPS_SERVICE_DOMAIN_NAME, metadata.getServiceDomainName()); } if (StringUtils.isNotBlank(metadata.getServiceNamespacePart())) { properties.setProperty(SOAProjectConstants.PROPS_SERVICE_NAMESPACE_PART, metadata.getServiceNamespacePart()); } properties.setProperty(SOAProjectConstants.PROPS_KEY_TYPE_FOLDING, Boolean.toString(metadata.getTypeFolding())); properties.setProperty(SOAProjectConstants.PROPS_SUPPORT_ZERO_CONFIG, Boolean.TRUE.toString()); ISOAConfigurationRegistry configReg = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem() .getConfigurationRegistry(); if (configReg != null && StringUtils.isNotBlank(configReg.getEnvironmentMapperImpl())) { properties.setProperty(SOAProjectConstants.PROPS_ENV_MAPPER, configReg.getEnvironmentMapperImpl()); } properties.setProperty(SOAProjectConstants.PROPS_KEY_SIPP_VERSION, SOAProjectConstants.PROPS_DEFAULT_SIPP_VERSION); //short package name for shared consumer final String intfPkgName = StringUtils.substringBeforeLast(metadata.getServiceInterface(), SOAProjectConstants.DELIMITER_DOT); properties.setProperty(SOAProjectConstants.PROPS_KEY_SHORT_PATH_FOR_SHARED_CONSUMER, intfPkgName + SOAProjectConstants.DELIMITER_DOT + SOAProjectConstants.GEN); properties.store(output, SOAProjectConstants.PROPS_COMMENTS); WorkspaceUtil.writeToFile(output.toString(), file, monitor); } finally { IOUtils.closeQuietly(output); } return file; }
From source file:org.ebayopensource.turmeric.eclipse.codegen.model.GenTypeServiceMetadataProps.java
@Override public Map<String, String> getCodeGenOptions() { Map<String, String> result = new TreeMap<String, String>(); if (getAdminName() != null) result.put(PARAM_ADMIN_NAME, getAdminName()); if (getNamespace() != null) result.put(PARAM_NAMESPACE, getNamespace()); if (getServiceLayerFile() != null) result.put(PARAM_SERVICE_LAYER_FILE, getServiceLayer()); if (getProjectRoot() != null) result.put(PARAM_PR, getProjectRoot()); if (getServiceName() != null) result.put(PARAM_SERVICE_NAME, getServiceName()); if (getServiceImplClassName() != null) { result.put(PARAM_SICN, getServiceImplClassName()); }//from ww w.j av a 2 s . c o m if (getServiceVersion() != null) result.put(PARAM_SCV, getServiceVersion()); if (getServiceLayer() != null) result.put(PARAM_SLAYER, getServiceLayer()); if (StringUtils.isNotBlank(getOriginalWsdlUrl())) { result.put(PARAM_WSDL, getOriginalWsdlUrl()); if (getServiceInterface().contains(".")) result.put(PARAM_GIP, StringUtils.substringBeforeLast(getServiceInterface(), ".")); result.put(PARAM_GIN, StringUtils.substringAfterLast(getServiceInterface(), ".")); } else { result.put(PARAM_INTERFACE, getServiceInterface()); } result.put(PARAM_GENTYPE, getGenType()); return result; }
From source file:org.ebayopensource.turmeric.eclipse.codegen.utils.CodeGenUtil.java
/** * Extracts the GIP value from the service interface name. Acts as a domain * wrapper over string utility class//w ww . j av a 2 s.com * * @param serviceInterface the service interface * @return the gIP from interface */ public static String getGIPFromInterface(String serviceInterface) { return StringUtils.substringBeforeLast(serviceInterface, "."); }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.codegen.model.TypeLibModelTransformer.java
private static String getXJCClassPath() throws CoreException, IOException { StringBuffer xjcClassPath = new StringBuffer(""); for (IProject typeLibProject : WorkspaceUtil .getProjectsByNature(TypeLibraryProjectNature.getTypeLibraryNatureId())) { xjcClassPath.append(typeLibProject.getLocation().toFile().getCanonicalPath()); xjcClassPath.append(File.pathSeparatorChar); }/*from w w w . j a va2 s . co m*/ return StringUtils.substringBeforeLast(xjcClassPath.toString(), File.pathSeparator); }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.actions.DeleteTypeAction.java
/** * {@inheritDoc}//from w w w . j a va 2s . c o m */ @Override public void run(final IAction action) { if (SOALogger.DEBUG) logger.entering(action, selection); try { if (selection == null) { showErrorDialog(); return; } if (!UIUtil.openChoiceDialog("Confirm Type Delete", "Are you sure you want to delete this type?", MessageDialog.QUESTION)) return; if (TypeLibraryUtil.isValidXSDFile(selection.getFirstElement())) { final IFile xsdFile = (IFile) selection.getFirstElement(); final IProject project = xsdFile.getProject(); final String fileName = StringUtils.substringBeforeLast(xsdFile.getName(), "." + xsdFile.getFileExtension()); final IFile episodeFile = project .getFile("gen-meta-src/META-INF/" + project.getName() + "/" + fileName + ".episode"); final IStatus status = ActionUtil.validateTypeDependencyAndProjectConfigFile(project, episodeFile); final String messages = ValidateUtil.getFormattedStatusMessagesForAction(status); if (messages != null) { UIUtil.showErrorDialog(UIUtil.getActiveShell(), "Error", messages, (Throwable) null); return; } File eFile = episodeFile.getLocation().toFile(); if (eFile.exists() == true) { File tmpFile = new File(eFile.getCanonicalPath() + ".bak"); try { if (tmpFile.exists()) { tmpFile.delete(); } if (eFile.renameTo(tmpFile) == false) { UIUtil.showErrorDialog(UIUtil.getActiveShell(), "Error", SOAMessages.ERR_DELETE_TYPE + eFile); return; } } catch (Exception e) { //the file could not be deleted, warn the user UIUtil.showErrorDialog(UIUtil.getActiveShell(), "Error", SOAMessages.ERR_DELETE_TYPE + eFile); return; } finally { if (tmpFile.exists()) { tmpFile.renameTo(eFile); } } } DeleteTypeAction.executeTypeDeletionTask((IFile) selection.getFirstElement()); } else { showErrorDialog(); return; } } catch (Exception e) { logger.error(e); UIUtil.showErrorDialog(e); } finally { if (SOALogger.DEBUG) logger.exiting(); } }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.actions.DeleteTypeAction.java
/** * Execute type deletion task./* w w w.j a v a 2 s .c o m*/ * * @param file the file * @throws CoreException the core exception * @throws Exception This is being used from the test apis. So please dont make it private */ public static void executeTypeDeletionTask(final IFile file) throws CoreException, Exception { LibraryType libraryType; SOAGlobalRegistryAdapter registryAdaptor = SOAGlobalRegistryAdapter.getInstance(); try { SOATypeRegistry typeRegistry = registryAdaptor.getGlobalRegistry(); libraryType = typeRegistry.getType(TypeLibraryUtil.toQName(file)); final List<LibraryType> childTypes = typeRegistry.getDependentChildTypeFiles(libraryType); if (!CollectionUtil.isEmpty(childTypes)) { StringBuilder msg = new StringBuilder( "SOA governance found the following types depending on this type: "); for (LibraryType libType : childTypes) { msg.append(libType.getName()); msg.append(", "); } String smsg = msg.toString(); smsg = StringUtils.substringBeforeLast(smsg, ","); UIUtil.showErrorDialog(null, "File cannot be deleted", "Type cannot be deleted", smsg); return; } else { WorkspaceJob job = new WorkspaceJob("Deleting type->" + file.getLocation()) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { SOAGlobalRegistryAdapter registryAdaptor = SOAGlobalRegistryAdapter.getInstance(); try { SOATypeRegistry typeRegistry = registryAdaptor.getGlobalRegistry(); monitor.beginTask("Deleting type->" + file.getLocation(), ProgressUtil.PROGRESS_STEP * 50); IProject project = file.getProject(); LibraryType libraryType = typeRegistry.getType(TypeLibraryUtil.toQName(file)); ProgressUtil.progressOneStep(monitor); typeRegistry.removeTypeFromRegistry(libraryType); ProgressUtil.progressOneStep(monitor); // file.delete(true, ProgressUtil // .getDefaultMonitor(null)); DeleteTypeAction.callCodegen(project, file, monitor); ProgressUtil.progressOneStep(monitor); WorkspaceUtil.refresh(monitor, project); registryAdaptor.populateRegistry(project.getName()); ProgressUtil.progressOneStep(monitor); SynchronizeWsdlAndDepXML synch = new SynchronizeWsdlAndDepXML(project); synch.syncronizeAllXSDsandDepXml(); ProgressUtil.progressOneStep(monitor); synch.synchronizeTypeDepandProjectDep(monitor); WorkspaceUtil.refresh(monitor, project); } catch (Exception e) { logger.error(e); throw new CoreException(EclipseMessageUtils.createErrorStatus(e)); } setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } } catch (Exception e) { WorkspaceUtil.refresh(file.getProject()); UIUtil.showErrorDialog(e); } }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java
/** * Just taking out the extn from the file name. Extn names could be changed * :)), You never know. This is just a dumb helper * * @param fileName the file name// w ww . j a v a2 s. c om * @return the xsd type name from file name */ public static String getXsdTypeNameFromFileName(String fileName) { String retValue = fileName; if (!StringUtils.isEmpty(fileName)) { retValue = StringUtils.substringBeforeLast(fileName, SOATypeLibraryConstants.EXT_XSD); } return retValue; }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java
/** * Gets the type name from protocol string. * * @param typeLibString the type lib string * @return the type name from protocol string *//* w w w.j a v a 2s. c om*/ public static String getTypeNameFromProtocolString(String typeLibString) { String retValue = null; if (!StringUtils.isEmpty(typeLibString) && typeLibString.startsWith(SOATypeLibraryConstants.TURMERIC_XSD_FILE_PROTOCOL)) { // removing type lib start string retValue = StringUtils.substringAfterLast(typeLibString, SOATypeLibraryConstants.PROTOCOL_DELIMITER); // removing xsd extn end string retValue = StringUtils.substringBeforeLast(retValue, SOATypeLibraryConstants.EXT_XSD); } return retValue; }