List of usage examples for org.apache.commons.lang StringUtils substringBefore
public static String substringBefore(String str, String separator)
Gets the substring before the first occurrence of a separator.
From source file:com.ewcms.component.util.Struts2Util.java
/** * ?contentTypeheaders.// w w w.j a va 2 s. c o m */ private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) { //?headers? String encoding = DEFAULT_ENCODING; boolean noCache = DEFAULT_NOCACHE; for (String header : headers) { String headerName = StringUtils.substringBefore(header, ":"); String headerValue = StringUtils.substringAfter(header, ":"); if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) { encoding = headerValue; } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) { 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) { ServletUtil.setNoCacheHeader(response); } return response; }
From source file:de.xirp.io.logging.XirpTextFieldAppender.java
/** * Extracts the robot name and the original message from the given * message./*from ww w . ja va2s. c om*/ * * @param message * the original message to extract the robot name and * original message from * @return a string array with the robot name and original message */ private String[] extractRobot(String message) { String robot = StringUtils.substringBetween(message, RobotLogger.ROBOT_IDENTIFIER, RobotLogger.ROBOT_DELIMITER); if (StringUtils.isEmpty(robot)) { return null; } String origMessage = StringUtils.substringBefore(message, RobotLogger.ROBOT_IDENTIFIER); origMessage += StringUtils.substringAfterLast(message, RobotLogger.ROBOT_DELIMITER); return new String[] { robot, origMessage }; }
From source file:fr.dutra.tools.maven.deptree.core.AbstractLineBasedParser.java
/** * When doing an install at the same time on a multi-module project, one can get this kind of output: * <pre>/*from ww w .j a v a2s. com*/ * +- active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = active project artifact: * artifact = com.acme.org:foobar:jar:1.0.41-SNAPSHOT:compile; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml; * project: MavenProject: com.acme.org:foobar:1.0.41-SNAPSHOT @ /opt/jenkins/home/jobs/foobar/workspace/trunk/foobar/pom.xml * </pre> */ protected String extractActiveProjectArtifact() { String artifact = null; //start at next line and consume all lines containing "artifact =" or "project: "; record the last line containing "artifact =". boolean artifactFound = false; while (this.lineIndex < this.lines.size() - 1) { String tempLine = this.lines.get(this.lineIndex + 1); boolean artifactLine = !artifactFound && tempLine.contains("artifact = "); boolean projectLine = artifactFound && tempLine.contains("project: "); if (artifactLine || projectLine) { if (tempLine.contains("artifact = ") && !tempLine.contains("active project artifact:")) { artifact = StringUtils.substringBefore(StringUtils.substringAfter(tempLine, "artifact = "), ";"); artifactFound = true; } this.lineIndex++; } else { break; } } return artifact; }
From source file:adalid.util.i18n.Mapper.java
private String base(File bundle) { String name = bundle.getName(); String base = _project + FILE_SEPARATOR; base += StringUtils.substringAfterLast(bundle.getParent(), join(_project)); if (name.contains("_")) { base = base + FILE_SEPARATOR + StringUtils.substringBefore(name, "_"); } else {/*www .j ava 2 s. c o m*/ base = base + FILE_SEPARATOR + StringUtils.substringBeforeLast(name, "."); } return base; }
From source file:ddf.mime.custom.CustomMimeTypeResolver.java
public void setCustomMimeTypes(String[] customMimeTypes) { LOGGER.trace("ENTERING: setCustomMimeTypes"); this.customMimeTypes = customMimeTypes.clone(); this.customFileExtensionsToMimeTypesMap = new HashMap<String, String>(); this.customMimeTypesToFileExtensionsMap = new HashMap<String, List<String>>(); for (String mimeTypeMapping : this.customMimeTypes) { LOGGER.trace(mimeTypeMapping);//from w w w . ja v a 2 s .c o m // mimeTypeMapping is of the form <file extension>=<mime type> // Examples: // nitf=image/nitf String fileExtension = StringUtils.substringBefore(mimeTypeMapping, "="); String mimeType = StringUtils.substringAfter(mimeTypeMapping, "="); customFileExtensionsToMimeTypesMap.put(fileExtension, mimeType); List<String> fileExtensions = (List<String>) customMimeTypesToFileExtensionsMap.get(mimeType); if (fileExtensions == null) { LOGGER.debug("Creating fileExtensions array for mime type: {}", mimeType); fileExtensions = new ArrayList<String>(); } LOGGER.debug("Adding file extension: {} for mime type: {}", fileExtensions, mimeType); fileExtensions.add(fileExtension); customMimeTypesToFileExtensionsMap.put(mimeType, fileExtensions); } LOGGER.debug("customFileExtensionsToMimeTypesMap = {} ", customFileExtensionsToMimeTypesMap); LOGGER.debug("customMimeTypesToFileExtensionsMap = {}", customMimeTypesToFileExtensionsMap); LOGGER.trace("EXITING: setCustomMimeTypes"); }
From source file:net.itransformers.idiscover.v2.core.node_discoverers.snmpdiscoverer.SnmpParallelNodeDiscoverer.java
@Override public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) { String deviceId = null;/*from w w w . ja va 2 s .co m*/ String deviceName = connectionDetails.getParam("deviceName"); String ipAddressStr = connectionDetails.getParam("ipAddress"); String deviceType = connectionDetails.getParam("deviceType"); Map<String, String> resourceSelectionParams = returnResourceSelectionParams(deviceName, deviceType, ipAddressStr); HashMap<String, String> resultParams = new HashMap<>(); NodeDiscoveryResult result = new NodeDiscoveryResult(); SnmpManager snmpManager = null; try { snmpManager = getSnmpManager(resourceSelectionParams, ipAddressStr); } catch (IOException e) { logger.error(e.getMessage()); } if (snmpManager != null) { String hostNameBySnmp = null; String deviceTypeBySnmp; try { String deviceSysDescr = snmpManager.snmpGet("1.3.6.1.2.1.1.1.0"); String hostNameBySnmpStr1 = snmpManager.snmpGet("1.3.6.1.2.1.1.5.0"); if (hostNameBySnmpStr1 != null) { if (hostNameBySnmpStr1.contains(".")) hostNameBySnmp = StringUtils.substringBefore(hostNameBySnmpStr1, "."); else hostNameBySnmp = hostNameBySnmpStr1; } else { logger.info( "Can't determine the hostname of " + ipAddressStr + " with " + resourceSelectionParams); return null; } deviceTypeBySnmp = DeviceTypeResolver.getDeviceType(deviceSysDescr); resultParams.put("hostName", hostNameBySnmp); resultParams.put("deviceType", deviceTypeBySnmp); resultParams.put("sysDescr", deviceSysDescr); } catch (IOException ioe) { logger.error(ioe.getMessage()); return null; } deviceId = hostNameBySnmp; DiscoveryHelper discoveryHelper = discoveryHelperFactory.createDiscoveryHelper(deviceTypeBySnmp); XmlDiscoveryHelperV2 discoveryHelperV2 = createXmlDiscoveryHelper(deviceTypeBySnmp); RawDeviceData rawData = getRawData(snmpManager, discoveryHelper); try { snmpManager.closeSnmp(); } catch (IOException e) { e.printStackTrace(); } DiscoveredDeviceData discoveredDeviceData = getDeviceData(discoveryHelper, rawData); DiscoveredDevice discoveredDevice = discoveryHelperV2.createDevice(discoveredDeviceData, deviceId); HashMap<String, String> deviceParams = discoveredDevice.getParams(); deviceParams.putAll(resultParams); discoveredDevice.setParams(deviceParams); List<DeviceNeighbour> neighbours = discoveredDevice.getDeviceNeighbours(); Set<Subnet> subnets = discoveredDevice.getDeviceSubnetsFromActiveInterfaces(); Set<ConnectionDetails> ownConnectionDetails = discoveredDevice.getDeviceOwnConnectionDetails(); Set<ConnectionDetails> neighboursConnDetails = new HashSet<ConnectionDetails>(); if (neighbours != null) { NeighbourConnectionDetails neighbourConnectionDetails = new NeighbourConnectionDetails(neighbours); neighboursConnDetails = neighbourConnectionDetails.getConnectionDetailses(); } if (subnets != null) { SubnetConnectionDetails subnetConnectionDetails1 = new SubnetConnectionDetails(); subnetConnectionDetails1.load(subnets); neighboursConnDetails.addAll(subnetConnectionDetails1.getSubnetConnectionDetails()); } result.setOwnConnectionDetails(ownConnectionDetails); result.setNeighboursConnectionDetails(neighboursConnDetails); result.setDiscoveredData("deviceData", discoveredDeviceData); result.setDiscoveredData("DiscoveredDevice", discoveredDevice); result.setDiscoveredData("rawData", rawData.getData()); result.setNodeId(deviceId); return result; } else { return null; } }
From source file:com.htmlhifive.tools.codeassist.core.proposal.checker.EventContextProposalChecker.java
@Override protected boolean doCheckCodeAssist(CompilationUnitDeclaration unitDeclaration) { NodeCollector collector = NodeCollectorFactory.createNodeCollector(getBean()); collector.collect(unitDeclaration);//from w w w . j a v a2s. c o m IASTNode[] eventHandlerNodes = collector.getNodes(); String eventContextName = null; for (IASTNode eventHandler : eventHandlerNodes) { MemberAccessVisitor visitor = new MemberAccessVisitor(); eventHandler.traverse(visitor); if (visitor.getMemberAccess() != null) { memberAccess = visitor.getMemberAccess(); IFunctionDeclaration funcDeclaration = (IFunctionDeclaration) eventHandler; IArgument arg = funcDeclaration.getArguments()[0]; // jsdoc????????? if (arg.getInferredType() != null) { return false; } eventContextName = String.valueOf(arg.getName()); } } if (memberAccess == null || eventContextName == null) { return false; } codeAssistStr = memberAccess.getReceiver().toString(); String firstSegMemberAccess = StringUtils.substringBefore(codeAssistStr, "."); if (StringUtils.equals(firstSegMemberAccess, eventContextName)) { this.addDummyCodeInfoList(new DelegateDummyCodeInfo(memberAccess.sourceEnd + 1, eventContextName, CodeBuilderType.CREATE_OBJ)); return true; } return false; }
From source file:eionet.gdem.qa.XQueryTask.java
/** * Run XQuery script: steps: - download the source from URL - run XQuery - store the result in a text file. *//* ww w . j av a2 s . c o m*/ @Override public void run() { try { LOGGER.info("Job ID= " + jobId + " started getting source file."); String srcFile = null; srcFile = url; // status to -processing changeStatus(Constants.XQ_PROCESSING); // Do validation if (queryID.equals(String.valueOf(Constants.JOB_VALIDATION))) { LOGGER.info("Job ID=" + jobId + " Validation started"); try { // validate only the first XML Schema if (scriptFile.contains(" ")) { scriptFile = StringUtils.substringBefore(scriptFile, " "); } LOGGER.info("** XQuery starts, ID=" + jobId + " schema: " + scriptFile + " result will be stored to " + resultFile); ValidationService vs = new ValidationService(); // XML Schema should be in schemaLocation attribute String result = vs.validateSchema(srcFile, scriptFile); LOGGER.debug("Validation proceeded, now store to the result file"); Utils.saveStrToFile(resultFile, result, null); } catch (Exception e) { handleError("Error during validation:" + e.toString(), true); return; } } else { // Do xq job LOGGER.info("Job ID=" + jobId + " XQ processing started"); // read query info from DB. Map query = getQueryInfo(queryID); String contentType = null; Schema schema = null; boolean schemaExpired = false; boolean isNotLatestReleasedDDSchema = false; if (query != null && query.containsKey("content_type")) { contentType = (String) query.get("content_type"); } // get script type if it comes from T_QUERY table if (query != null && query.containsKey("script_type")) { scriptType = (String) query.get("script_type"); } // stylesheet - to check if it is expired if (query != null && query.containsKey("xml_schema")) { // set schema if exists: schema = getSchema((String) query.get("xml_schema")); schemaExpired = (schema != null && schema.isExpired()); isNotLatestReleasedDDSchema = DataDictUtil.isDDSchemaAndNotLatestReleased(schema.getSchema()); } // get script type if it stored in filesystem and we have to // guess it by file extension if (Utils.isNullStr(scriptType)) { scriptType = scriptFile.endsWith(XQScript.SCRIPT_LANG_XSL) ? XQScript.SCRIPT_LANG_XSL : scriptFile.endsWith(XQScript.SCRIPT_LANG_XGAWK) ? XQScript.SCRIPT_LANG_XGAWK : XQScript.SCRIPT_LANG_XQUERY1; } String[] xqParam = { Constants.XQ_SOURCE_PARAM_NAME + "=" + srcFile }; try { if (scriptFile.contains(" ")) { scriptFile = StringUtils.substringBefore(scriptFile, " "); } LOGGER.info("** XQuery starts, ID=" + jobId + " params: " + (xqParam == null ? "<< no params >>" : xqParam[0]) + " result will be stored to " + resultFile); LOGGER.debug("Script: \n" + scriptFile); XQScript xq = new XQScript(null, xqParam, contentType); xq.setScriptFileName(scriptFile); xq.setScriptType(scriptType); xq.setSrcFileUrl(srcFile); xq.setSchema(schema); if (XQScript.SCRIPT_LANG_FME.equals(scriptType)) { if (query != null && query.containsKey("url")) { xq.setScriptSource((String) query.get("url")); } } FileOutputStream out = null; try { // if result type is HTML and schema is expired parse // result (add warning) before writing to file if ((schemaExpired || isNotLatestReleasedDDSchema) && contentType.equals(XQScript.SCRIPT_RESULTTYPE_HTML)) { String res = xq.getResult(); Utils.saveStrToFile(resultFile, res, null); } else { out = new FileOutputStream(new File(resultFile)); xq.getResult(out); } } catch (IOException ioe) { throw new GDEMException(ioe.toString()); } catch (GDEMException e) { // store error in feedback, it could be XML processing error StringBuilder errBuilder = new StringBuilder(); errBuilder.append( "<div class=\"feedbacktext\"><span id=\"feedbackStatus\" class=\"BLOCKER\" style=\"display:none\">Unexpected error occured!</span><h2>Unexpected error occured!</h2>"); errBuilder.append(Utils.escapeXML(e.toString())); errBuilder.append("</div>"); IOUtils.write(errBuilder.toString(), out); } finally { IOUtils.closeQuietly(out); } LOGGER.debug("Script proceeded, now store to the result file"); } catch (Exception e) { handleError("Error processing QA script:" + e.toString(), true); return; } } changeStatus(Constants.XQ_READY); // TODO: Change to failed if script has failed LOGGER.info("Job ID=" + jobId + " succeeded"); // all done, thread stops here, job is waiting for pulling from the // client side } catch (Exception ee) { handleError("Error in thread run():" + ee.toString(), true); } }
From source file:de.hybris.platform.acceleratorservices.payment.cybersource.strategies.impl.DefaultPaymentTransactionStrategy.java
@Override public void setPaymentTransactionReviewResult(final PaymentTransactionEntryModel reviewDecisionEntry, final String guid) { if (reviewDecisionEntry == null || guid == null) { return;/* w w w. java 2 s.com*/ } OrderModel order = new OrderModel(); // the guid is the merchant id composed of order.guid + -<number> for example: 599b141c2dc0a5d2ecf6735d2c9fb7a7416d83fa-1 // we want to search for an order using the original guid order.setGuid(StringUtils.substringBefore(guid, "-")); order = getFlexibleSearchService().getModelByExample(order); final PaymentTransactionModel transaction = (order.getPaymentTransactions().iterator().hasNext() ? order.getPaymentTransactions().iterator().next() : null); if (checkIfAuthorizationWaitForReview(transaction)) { reviewDecisionEntry.setPaymentTransaction(transaction); reviewDecisionEntry.setCode(getPaymentService().getNewPaymentTransactionEntryCode(transaction, PaymentTransactionType.REVIEW_DECISION)); getModelService().save(reviewDecisionEntry); //send an event getBusinessProcessService().triggerEvent(transaction.getOrder().getCode() + REVIEW_DECISION_EVENT_NAME); } }
From source file:com.haulmont.cuba.core.sys.javacl.JavaClassLoader.java
@Override public Class loadClass(final String fullClassName, boolean resolve) throws ClassNotFoundException { String containerClassName = StringUtils.substringBefore(fullClassName, "$"); StopWatch loadingWatch = new Slf4JStopWatch("LoadClass"); try {//from ww w. ja v a2 s .c o m lock(containerClassName); Class clazz; if (!sourceProvider.getSourceFile(containerClassName).exists()) { clazz = super.loadClass(fullClassName, resolve); return clazz; } CompilationScope compilationScope = new CompilationScope(this, containerClassName); if (!compilationScope.compilationNeeded()) { TimestampClass timestampClass = getTimestampClass(fullClassName); if (timestampClass == null) { throw new ClassNotFoundException(fullClassName); } return timestampClass.clazz; } String src; try { src = sourceProvider.getSourceString(containerClassName); } catch (IOException e) { throw new ClassNotFoundException("Could not load java sources for class " + containerClassName); } try { log.debug("Compiling " + containerClassName); final DiagnosticCollector<JavaFileObject> errs = new DiagnosticCollector<>(); SourcesAndDependencies sourcesAndDependencies = new SourcesAndDependencies(rootDir, this); sourcesAndDependencies.putSource(containerClassName, src); sourcesAndDependencies.collectDependencies(containerClassName); Map<String, CharSequence> sourcesForCompilation = sourcesAndDependencies .collectSourcesForCompilation(containerClassName); @SuppressWarnings("unchecked") Map<String, Class> compiledClasses = createCompiler().compile(sourcesForCompilation, errs); Map<String, TimestampClass> compiledTimestampClasses = wrapCompiledClasses(compiledClasses); compiled.putAll(compiledTimestampClasses); linkDependencies(compiledTimestampClasses, sourcesAndDependencies.dependencies); clazz = compiledClasses.get(fullClassName); springBeanLoader.updateContext(compiledClasses.values()); return clazz; } catch (Exception e) { proxyClassLoader.restoreRemoved(); throw new RuntimeException(e); } finally { proxyClassLoader.cleanupRemoved(); } } finally { unlock(containerClassName); loadingWatch.stop(); } }