List of usage examples for org.apache.commons.lang StringUtils substringAfter
public static String substringAfter(String str, String separator)
Gets the substring after the first occurrence of a separator.
From source file:com.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java
private static String unpackJar(URL resource) { String file = resource.getPath(); if (file.contains(".jar!/")) { s_logger.info("Unpacking zip file located within a jar file: {}", resource); String jarFileName = StringUtils.substringBefore(file, "!/"); if (jarFileName.startsWith("file:/")) { jarFileName = jarFileName.substring(5); if (SystemUtils.IS_OS_WINDOWS) { jarFileName = StringUtils.stripStart(jarFileName, "/"); }//from w w w. j a va 2 s . c o m } else if (jarFileName.startsWith("file:/")) { jarFileName = jarFileName.substring(6); } jarFileName = StringUtils.replace(jarFileName, "%20", " "); String innerFileName = StringUtils.substringAfter(file, "!/"); innerFileName = StringUtils.replace(innerFileName, "%20", " "); s_logger.info("Unpacking zip file found jar file: {}", jarFileName); s_logger.info("Unpacking zip file found zip file: {}", innerFileName); try { JarFile jar = new JarFile(jarFileName); JarEntry jarEntry = jar.getJarEntry(innerFileName); try (InputStream in = jar.getInputStream(jarEntry)) { File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip"); tempFile.deleteOnExit(); try (OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } file = tempFile.getCanonicalPath(); } } catch (IOException ex) { throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex); } s_logger.debug("Unpacking zip file extracted to: {}", file); } return file; }
From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java
@SuppressWarnings("unchecked") protected <R> ModelAndView forward(HttpServletRequest httpServletRequest, UrlTemplateBinder<R> urlBinder, String urlTemplate, R resource, String byUriTemplate, boolean redirect) { String url = this.urlTemplateBindingCreator.bindResourceToUrlTemplate(urlBinder, resource, urlTemplate); String extraUrlPath = StringUtils.substringAfter(httpServletRequest.getRequestURI(), StringUtils.removeEnd(byUriTemplate, ALL_WILDCARD)); if (StringUtils.isNotBlank(extraUrlPath)) { url = url + "/" + extraUrlPath; }//from w w w . j a v a2 s.c om ModelAndView mav; if (redirect) { Map<String, Object> parameters = new HashMap<String, Object>(httpServletRequest.getParameterMap()); parameters.remove(PARAM_REDIRECT); parameters.remove(PARAM_URI); mav = new ModelAndView("redirect:" + url + this.mapToQueryString(parameters)); } else { mav = new ModelAndView("forward:" + url); } return mav; }
From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java
/** * @throws MessagingException/*from w w w. ja v a2 s.c om*/ */ private void loadMailFolder() throws MessagingException { log.debug("loading folder tree..."); long millis = System.currentTimeMillis(); this.mailFolderMap.clear(); this.mailFolderList.clear(); Folder defaultFolder = this.store.getDefaultFolder(); this.folderSeparator = defaultFolder.getSeparator(); // read all folders to a map List<String> topFolderNames = new ArrayList<String>(); Folder[] allFolders = defaultFolder.list("*"); if (allFolders != null && allFolders.length > 0) { for (Folder folder : allFolders) { this.mailFolderMap.put(folder.getFullName(), createMailFolder(folder)); if (SessionManager.get().getPreferences().getInboxFolderName().equals(folder.getFullName())) { topFolderNames.add(0, SessionManager.get().getPreferences().getInboxFolderName()); } else { String folderName = folder.getFullName(); if (!StringUtils.isEmpty(this.personalNameSpace) && folderName.startsWith(this.personalNameSpace)) { folderName = StringUtils.substringAfter(folderName, this.personalNameSpace); } if (StringUtils.countMatches(folderName, String.valueOf(getFolderSeparator())) == 0) { topFolderNames.add(folder.getFullName()); } } } } // build the tree structure for (String folderName : topFolderNames) { IMailFolder mailFolder = this.mailFolderMap.get(folderName); this.mailFolderList.add(mailFolder); if (mailFolder.hasChildren()) { mailFolder.setSubfolders(getSubfolders(mailFolder)); } } log.debug("...finish: " + (System.currentTimeMillis() - millis) + "ms"); }
From source file:com.amalto.core.storage.SystemStorageWrapper.java
@Override public long deleteDocument(String clusterName, String uniqueID, String documentType) throws XmlServerException { Storage storage = getStorage(clusterName); ComplexTypeMetadata type = getType(clusterName, storage, uniqueID); if (type == null) { return -1; }//w ww .j ava 2 s . c o m if (DROPPED_ITEM_TYPE.equals(type.getName())) { // head.Product.Product.0- uniqueID = uniqueID.substring(0, uniqueID.length() - 1); uniqueID = StringUtils.substringAfter(uniqueID, "."); //$NON-NLS-1$ } else if (!COMPLETED_ROUTING_ORDER.equals(type.getName()) && !FAILED_ROUTING_ORDER.equals(type.getName()) && !CUSTOM_FORM_TYPE.equals(type.getName()) && !SYNCHRONIZATION_OBJECT_TYPE.equals(type.getName())) { if (uniqueID.startsWith(PROVISIONING_PREFIX_INFO)) { uniqueID = StringUtils.substringAfter(uniqueID, PROVISIONING_PREFIX_INFO); } else if (uniqueID.startsWith(BROWSEITEM_PREFIX_INFO)) { uniqueID = StringUtils.substringAfter(uniqueID, BROWSEITEM_PREFIX_INFO); //$NON-NLS-1$ } else if (uniqueID.contains(".")) { //$NON-NLS-1$ uniqueID = StringUtils.substringAfterLast(uniqueID, "."); //$NON-NLS-1$ } } long start = System.currentTimeMillis(); { UserQueryBuilder qb = from(type).where(eq(type.getKeyFields().iterator().next(), uniqueID)); StorageResults results = null; try { storage.begin(); Select select = qb.getSelect(); results = storage.fetch(select); if (results.getCount() == 0) { throw new IllegalArgumentException("Could not find document to delete."); //$NON-NLS-1$ } storage.delete(select); storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } finally { if (results != null) { results.close(); } } } return System.currentTimeMillis() - start; }
From source file:com.cubusmail.mail.imap.IMAPMailbox.java
/** * @param mailFolder/*w w w . j a va 2s .c om*/ * @return * @throws MessagingException */ private List<IMailFolder> getSubfolders(IMailFolder mailFolder) throws MessagingException { List<IMailFolder> subfolders = new ArrayList<IMailFolder>(); String searchKey = mailFolder.getId() + getFolderSeparator(); Set<String> keys = this.mailFolderMap.keySet(); for (String key : keys) { if (key.startsWith(searchKey) && !StringUtils.contains(StringUtils.substringAfter(key, searchKey), getFolderSeparator())) { IMailFolder subfolder = this.mailFolderMap.get(key); subfolders.add(subfolder); if (subfolder.hasChildren()) { subfolder.setSubfolders(getSubfolders(subfolder)); } } } return subfolders; }
From source file:com.amalto.core.server.DefaultItem.java
/** * Returns an ordered collection of results searched in a cluster and specifying an optional condition<br/> * The results are xml objects made of elements constituted by the specified viewablePaths * * @param dataClusterPOJOPK The Data Cluster where to run the query * @param forceMainPivot An optional pivot that will appear first in the list of pivots in the query<br> * : This allows forcing cartesian products: for instance Order Header vs Order Line * @param viewablePaths The list of elements returned in each result * @param whereItem The condition/* w w w . jav a 2s .com*/ * @param spellThreshold The condition spell checking threshold. A negative value de-activates spell * @param orderBy The full path of the item user to order * @param direction One of {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_ASCENDING} or * {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_DESCENDING} * @param start The first item index (starts at zero) * @param limit The maximum number of items to return * @param returnCount True if total search count should be returned as first result. * @return The ordered list of results * @throws com.amalto.core.util.XtentisException In case of error in MDM code. */ @Override public ArrayList<String> xPathsSearch(DataClusterPOJOPK dataClusterPOJOPK, String forceMainPivot, ArrayList<String> viewablePaths, IWhereItem whereItem, int spellThreshold, String orderBy, String direction, int start, int limit, boolean returnCount) throws XtentisException { try { if (viewablePaths.size() == 0) { String err = "The list of viewable xPaths must contain at least one element"; LOGGER.error(err); throw new XtentisException(err); } // Check if user is allowed to read the cluster ILocalUser user = LocalUser.getLocalUser(); boolean authorized = false; String dataModelName = dataClusterPOJOPK.getUniqueId(); if (MDMConfiguration.getAdminUser().equals(user.getUsername())) { authorized = true; } else if (user.userCanRead(DataClusterPOJO.class, dataModelName)) { authorized = true; } if (!authorized) { throw new XtentisException("Unauthorized read access on data cluster '" + dataModelName + "' by user '" + user.getUsername() + "'"); } Server server = ServerContext.INSTANCE.get(); String typeName = StringUtils.substringBefore(viewablePaths.get(0), "/"); //$NON-NLS-1$ StorageAdmin storageAdmin = server.getStorageAdmin(); Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName)); MetadataRepository repository = storage.getMetadataRepository(); ComplexTypeMetadata type = repository.getComplexType(typeName); UserQueryBuilder qb = from(type); qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository)); qb.start(start); qb.limit(limit); if (orderBy != null) { List<TypedExpression> fields = UserQueryHelper.getFields(type, StringUtils.substringAfter(orderBy, "/")); //$NON-NLS-1$ if (fields == null) { throw new IllegalArgumentException("Field '" + orderBy + "' does not exist."); } OrderBy.Direction queryDirection; if ("ascending".equals(direction)) { //$NON-NLS-1$ queryDirection = OrderBy.Direction.ASC; } else { queryDirection = OrderBy.Direction.DESC; } for (TypedExpression field : fields) { qb.orderBy(field, queryDirection); } } // Select fields for (String viewablePath : viewablePaths) { String viewableTypeName = StringUtils.substringBefore(viewablePath, "/"); //$NON-NLS-1$ String viewableFieldName = StringUtils.substringAfter(viewablePath, "/"); //$NON-NLS-1$ if (!viewableFieldName.isEmpty()) { qb.select(repository.getComplexType(viewableTypeName), viewableFieldName); } else { qb.selectId(repository.getComplexType(viewableTypeName)); // Select id if xPath is 'typeName' and not 'typeName/field' } } ArrayList<String> resultsAsString = new ArrayList<String>(); StorageResults results; try { storage.begin(); if (returnCount) { results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ } results = storage.fetch(qb.getSelect()); DataRecordWriter writer = new DataRecordDefaultWriter(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { writer.write(result, output); } catch (IOException e) { throw new XmlServerException(e); } String document = new String(output.toByteArray()); resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } return resultsAsString; } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:com.lily.dap.web.util.Struts2Utils.java
/** * ./* ww w. j av a 2 s . co m*/ * * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain", * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK", * "no-cache:false"); * * @param headers * header"encoding:""no-cache:",UTF-8true. */ public static void render(final String contentType, final String content, final String... headers) { try { // headers String encoding = ENCODING_DEFAULT; boolean noCache = NOCACHE_DEFAULT; for (String header : headers) { String headerName = StringUtils.substringBefore(header, ":"); String headerValue = StringUtils.substringAfter(header, ":"); if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) { encoding = headerValue; } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) { noCache = Boolean.parseBoolean(headerValue); } else throw new IllegalArgumentException(headerName + "header"); } HttpServletResponse response = ServletActionContext.getResponse(); // headers String fullContentType = contentType + ";charset=" + encoding; response.setContentType(fullContentType); if (noCache) { WebUtils.setNoCacheHeader(response); } response.getWriter().write(content); response.getWriter().flush(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:adalid.core.AbstractArtifact.java
/** * @return the partial name//from w w w . j a v a 2s .c om */ @Override public String getPartialName() { return StringUtils.substringAfter(getPathString(), "." + "this" + "."); }
From source file:eionet.cr.dao.helpers.CsvImportHelper.java
/** * Extracts object from csv row./*w w w .j a v a2 s.c o m*/ * * @param line * @param objectsTypeUri * @return */ private SubjectDTO extractObject(String[] line, String objectsTypeUri) { // Construct subject URI and DTO object. String subjectUri = fileUri + "/" + extractObjectId(line); SubjectDTO subject = new SubjectDTO(subjectUri, false); // Add rdf:type to DTO. ObjectDTO typeObject = new ObjectDTO(objectsTypeUri, false); typeObject.setSourceUri(fileUri); subject.addObject(Predicates.RDF_TYPE, typeObject); // Add all other values. for (int i = 0; i < columns.size(); i++) { // If current columns index out of bounds for some reason, then break. if (i >= line.length) { break; } // Get column title, skip this column if it's the label column, otherwise replace spaces. String column = columns.get(i); // Extract column type and language code String type = StringUtils.substringAfter(column, ":"); if (type != null && type.length() == 0) { type = null; } String lang = StringUtils.substringAfter(column, "@"); if (lang != null && lang.length() == 0) { lang = null; } // Get column label column = columnLabels.get(i); column = column.replace(" ", "_"); // Create ObjectDTO representing the given column's value on this line ObjectDTO objectDTO = createValueObject(column, line[i], type, lang); objectDTO.setSourceUri(fileUri); // Add ObjectDTO to the subject. String predicateUri = fileUri + "#" + column; subject.addObject(predicateUri, objectDTO); } return subject; }
From source file:io.ecarf.core.utils.LogParser.java
/** * //from w w w .j ava 2s .c om * @throws FileNotFoundException * @throws IOException */ private void parse() throws FileNotFoundException, IOException { System.out.println("Parsing log files: "); for (String file : files) { boolean coordinator = file.contains(COORDINATOR); Stats stats; Stats dStats = null; List<Double> bigQuerySave = null; List<Double> bigQueryLoad = null; List<Double> bigQueryQueriesElapsed = null; if (coordinator) { stats = new CoordinatorStats(); this.coordinators.add((CoordinatorStats) stats); } else { stats = new ProcessorStats(); this.processors.add((ProcessorStats) stats); bigQuerySave = new ArrayList<>(); bigQueryLoad = new ArrayList<>(); bigQueryQueriesElapsed = new ArrayList<>(); dStats = new DictionaryStats(); dStats.filename = StringUtils.substringAfterLast(file, "/"); this.dictionaries.add((DictionaryStats) dStats); } stats.filename = StringUtils.substringAfterLast(file, "/"); //System.out.println(file); String line = null; int rows = 0; int inferred = 0; try (BufferedReader r = new BufferedReader(new FileReader(file))) { do { line = r.readLine(); if (line != null) { if (line.indexOf(TIMER) > -1) { this.parseTaskTimer(stats, line, coordinator); } else if (line.indexOf(ELAPSED_JOB) > -1 && coordinator) { ((CoordinatorStats) stats).endToEnd = this.extractAndGetTimer(line, ELAPSED_JOB); } else if (line.indexOf(REASON_TASK_SUMMARY) > -1) { this.extractProcessorReasoningStats(line, (ProcessorStats) stats); } else if (line.indexOf(BIGQUERY_SAVE) > -1) { bigQuerySave.add(this.extractAndGetTimer(line, BIGQUERY_SAVE, true)); } else if (line.contains(BIGQUERY_ROWS)) { rows = Integer.parseInt(StringUtils.substringBetween(line, DOWNLOADING, BIGQUERY_ROWS)); } else if (line.indexOf(BIGQUERY_JOB_ELAPSED) > -1) { double value = this.extractAndGetTimer(line, BIGQUERY_JOB_ELAPSED, true); r.readLine(); String line1 = r.readLine(); if (line1 != null && line1.indexOf("\"configuration\" : {") > -1) { line1 = r.readLine(); if (line1.indexOf("\"load\" : {") > -1) { bigQueryLoad.add(value); if (inferred > 0) { this.bigQueryImport.add(new Rows(inferred, value)); inferred = 0; } } else if (line1.indexOf("\"query\" : {") > -1) { // fast forward to this line //"recordsWritten" : "0", do { line1 = r.readLine(); } while (line1 != null && !line1.contains("\"recordsWritten\" :")); if (line1 != null && !line1.contains("\"recordsWritten\" : \"0\",")) { if (value > 0) { bigQueryQueriesElapsed.add(value); } } } else if (line1.indexOf("\"extract\" : {") > -1) { if (rows > 0) { this.bigQueryExport.add(new Rows(rows, value)); rows = 0; } } } } else if (line.indexOf(ASSEMBLE_DICTIONARY_SUBTASK) > -1 || line.contains(ASSEMBLE_DICT_TASK) || line.contains(TERM_DICT_CON) || line.contains(TERM_DICT)) { this.extractDictionaryStats((DictionaryStats) dStats, line); } else if (coordinator) { if (line.contains(JSON_NUM_VM)) { //"numberOfProcessors": 8.0 ((CoordinatorStats) stats).numOfProcessors = (int) Double .parseDouble(StringUtils.substringAfter(line, JSON_NUM_VM + " ")); } else if (line.contains(JSON_VM_TYPE)) { //"vmType": "n1-standard-2", ((CoordinatorStats) stats).vmType = StringUtils.substringBetween(line, JSON_VM_TYPE + " \"", "\","); } } else if (!coordinator && line.contains(FILE_ITEMS)) { // line occurs twice per file, so only add if hasn't been added yet if (((ProcessorStats) stats).fileItems.isEmpty()) { String items = StringUtils.substringAfter(line, FILE_ITEMS); //processor.files.ProcessFilesTask - Processing files: [revision_ids_en.nt.gz, revision_uris_en.nt.gz, yago_taxonomy.nt.gz, interlanguage_links_chapters_en.nt.gz, geo_coordinates_en.nt.gz] List<String> fileItems = Lists .newArrayList(StringUtils.substringBetween(items, "[", "]").split(", ")); ((ProcessorStats) stats).fileItems.addAll(fileItems); } } else if (line.contains(DICT_DOWNLOAD)) { //task.processor.ProcessLoadTask - Loading the dictionary from file: /tmp/dbpedia_dictionary.kryo.gz, memory usage: 1.8702433556318283GB, timer: 9.671 s ((ProcessorStats) stats).dictionaryDowload = this.extractAndGetTimer(line, TIMER_PREFIX, true); double[] values = this.extractAndGetMemoryDictionaryItems(line); ((ProcessorStats) stats).dictionaryMemBefore = values[0]; } else if (line.contains(DICT_LOAD)) { //task.processor.ProcessLoadTask - Dictionary loaded successfully, memory usage: 3.9780617877840996GB, timer: 1.160 min ((ProcessorStats) stats).dictionaryLoad = this.extractAndGetTimer(line, TIMER_PREFIX); double[] values = this.extractAndGetMemoryDictionaryItems(line); ((ProcessorStats) stats).dictionaryMemAfter = values[0]; } if (line.contains(BIGQUERY_INF)) { //System.out.println(line); if (line.contains("DoReasonTask8")) { inferred = Integer .parseInt(StringUtils.substringBetween(line, INSERTING8, BIGQUERY_INF)); } else { inferred = Integer .parseInt(StringUtils.substringBetween(line, INSERTING, BIGQUERY_INF)); } } } } while (line != null); } if (!coordinator) { ((ProcessorStats) stats).bigQuerySave = this.sum(bigQuerySave); ((ProcessorStats) stats).bigQueryInsert = this.sum(bigQueryLoad); if (!bigQueryQueriesElapsed.isEmpty()) { ((ProcessorStats) stats).bigQueryAverageQuery = this.sum(bigQueryQueriesElapsed) / bigQueryQueriesElapsed.size(); } } } //if(!this.jobElapsedTimes.isEmpty()) { // this.coordinators.get(0).endToEnd = this.jobElapsedTimes.get(this.jobElapsedTimes.size() - 1); //} }