List of usage examples for org.apache.commons.lang StringUtils stripEnd
public static String stripEnd(String str, String stripChars)
Strips any of a set of characters from the end of a String.
From source file:org.restcomm.connect.http.cors.CorsFilter.java
private void initLazily(ServletRequest request) { if (lazyServletContext == null) { ServletContext context = request.getServletContext(); String rootPath = context.getRealPath("/"); rootPath = StringUtils.stripEnd(rootPath, "/"); // remove trailing "/" character String restcommXmlPath = rootPath + "/WEB-INF/conf/restcomm.xml"; // ok, found restcomm.xml. Now let's get rcmlserver/base-url configuration setting File restcommXmlFile = new File(restcommXmlPath); // Create apache configuration XMLConfiguration apacheConf = new XMLConfiguration(); apacheConf.setDelimiterParsingDisabled(true); apacheConf.setAttributeSplittingDisabled(true); try {/*www .j av a 2 s.co m*/ apacheConf.load(restcommXmlPath); } catch (ConfigurationException e) { e.printStackTrace(); } // Create high-level configuration ConfigurationSource source = new ApacheConfigurationSource(apacheConf); RcmlserverConfigurationSet rcmlserverConfig = new RcmlserverConfigurationSetImpl(source); // initialize allowedOrigin String baseUrl = rcmlserverConfig.getBaseUrl(); if (baseUrl != null && (!baseUrl.trim().equals(""))) { // baseUrl is set. We need to return CORS allow headers allowedOrigin = baseUrl; } lazyServletContext = context; logger.info("Initialized (lazily) CORS servlet response filter. allowedOrigin: " + allowedOrigin); } }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClient.java
public void checkSchema(String[] clientConfigLocations) throws ClientPoolException, StorageClientException { checkClosed();//from w w w. ja v a 2 s. c o m Statement statement = null; try { statement = jcbcStorageClientConnection.getConnection().createStatement(); try { statement.execute(getSql(SQL_CHECKSCHEMA)); inc("schema"); LOGGER.info("Schema Exists"); return; } catch (SQLException e) { LOGGER.info("Schema does not exist {}", e.getMessage()); } for (String clientSQLLocation : clientConfigLocations) { String clientDDL = clientSQLLocation + ".ddl"; InputStream in = this.getClass().getClassLoader().getResourceAsStream(clientDDL); if (in != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); int lineNo = 1; String line = br.readLine(); StringBuilder sqlStatement = new StringBuilder(); while (line != null) { line = StringUtils.stripEnd(line, null); if (!line.isEmpty()) { if (line.startsWith(SQL_COMMENT)) { LOGGER.info("Comment {} ", line); } else if (line.endsWith(SQL_EOL)) { sqlStatement.append(line.substring(0, line.length() - 1)); String ddl = sqlStatement.toString(); try { statement.executeUpdate(ddl); LOGGER.info("SQL OK {}:{} {} ", new Object[] { clientDDL, lineNo, ddl }); } catch (SQLException e) { LOGGER.warn("SQL ERROR {}:{} {} {} ", new Object[] { clientDDL, lineNo, ddl, e.getMessage() }); } sqlStatement = new StringBuilder(); } else { sqlStatement.append(line); } } line = br.readLine(); lineNo++; } br.close(); LOGGER.info("Schema Created from {} ", clientDDL); break; } catch (Throwable e) { LOGGER.error("Failed to load Schema from {}", clientDDL, e); } finally { try { in.close(); } catch (IOException e) { LOGGER.error("Failed to close stream from {}", clientDDL, e); } } } else { LOGGER.info("No Schema found at {} ", clientDDL); } } } catch (SQLException e) { LOGGER.info("Failed to create schema ", e); throw new ClientPoolException("Failed to create schema ", e); } finally { try { statement.close(); dec("schema"); } catch (Throwable e) { LOGGER.debug("Failed to close statement in validate ", e); } } }
From source file:org.sakaiproject.tool.assessment.services.GradingService.java
/** * CALCULATED_QUESTION/* w w w. j a va2s .c om*/ * applyPrecisionToNumberString() takes a string representation of a number and returns * a string representation of that number, rounded to the specified number of * decimal places, including trimming decimal places if needed. * Will also throw away the extra trailing zeros as well as removing a trailing decimal point. * @param numberStr * @param decimalPlaces * @return processed number string (will never be null or empty string) */ public String applyPrecisionToNumberString(String numberStr, int decimalPlaces) { // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(numberStr); bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); String decimal = "."; // TODO handle localized decimal separator? //DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale); //char dec = dfs.getDecimalFormatSymbols().getDecimalSeparator(); String displayAnswer = bd.toString(); if (displayAnswer.length() > 2 && displayAnswer.contains(decimal)) { if (decimalPlaces == 0) { // Remove ".0" if decimalPlaces == 0 displayAnswer = displayAnswer.replace(decimal + "0", ""); } else { // trim away all the extra 0s from the end of the number if (displayAnswer.endsWith("0")) { displayAnswer = StringUtils.stripEnd(displayAnswer, "0"); } if (displayAnswer.endsWith(decimal)) { displayAnswer = displayAnswer.substring(0, displayAnswer.length() - 1); } } } return displayAnswer; }
From source file:org.sonar.java.checks.verifier.CheckVerifier.java
protected void collectExpectedIssues(String comment, int line) { String expectedStart = getExpectedIssueTrigger(); if (comment.startsWith(expectedStart)) { String cleanedComment = StringUtils.remove(comment, expectedStart); EnumMap<IssueAttribute, String> attr = new EnumMap<>(IssueAttribute.class); String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}"); if (StringUtils.isNotEmpty(expectedMessage)) { attr.put(IssueAttribute.MESSAGE, expectedMessage); }//from w ww . j av a 2 s . c o m int expectedLine = line; String attributesSubstr = extractAttributes(comment, attr); cleanedComment = StringUtils .stripEnd(StringUtils.remove(StringUtils.remove(cleanedComment, "[[" + attributesSubstr + "]]"), "{{" + expectedMessage + "}}"), " \t"); if (StringUtils.startsWith(cleanedComment, "@")) { final int lineAdjustment; final char firstChar = cleanedComment.charAt(1); final int endIndex = cleanedComment.indexOf(' '); if (endIndex == -1) { lineAdjustment = Integer.parseInt(cleanedComment.substring(2)); } else { lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex)); } if (firstChar == '+') { expectedLine += lineAdjustment; } else if (firstChar == '-') { expectedLine -= lineAdjustment; } else { Fail.fail("Use only '@+N' or '@-N' to shifts messages."); } } updateEndLine(expectedLine, attr); expected.put(expectedLine, attr); } }
From source file:org.structr.server.Structr.java
/** * Start the structr server with the previously specified configuration. * //www .ja va 2s. c o m * @throws IOException * @throws InterruptedException * @throws Exception */ public Server start(boolean waitForExit, boolean isTest) throws IOException, InterruptedException, Exception { String sourceJarName = app.getProtectionDomain().getCodeSource().getLocation().toString(); if (!isTest && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) { String jarFile = System.getProperty("jarFile"); if (StringUtils.isEmpty(jarFile)) { throw new IllegalArgumentException(app.getName() + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n" + "Please specify the path to the JAR file in the parameter -DjarFile.\n" + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar"); } sourceJarName = jarFile; } // get current base path basePath = System.getProperty("home", basePath); if (basePath.isEmpty()) { // use cwd and, if that fails, /tmp as a fallback basePath = System.getProperty("user.dir", "/tmp"); } // create base directory if it does not exist File baseDir = new File(basePath); if (!baseDir.exists()) { baseDir.mkdirs(); } configuredServices.add(ModuleService.class); configuredServices.add(NodeService.class); configuredServices.add(AgentService.class); configuredServices.add(CronService.class); configuredServices.add(LogService.class); File confFile = checkStructrConf(basePath, sourceJarName); Properties configuration = getConfiguration(confFile); checkPrerequisites(configuration); Server server = new Server(restPort); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.addHandler(new DefaultHandler()); List<Connector> connectors = new LinkedList<Connector>(); ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true); // create resource collection from base path & source JAR servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath), JarResource.newJarResource(Resource.newResource(sourceJarName)))); servletContext.setInitParameter("configfile.path", confFile.getAbsolutePath()); // this is needed for the filters to work on the root context "/" servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/"); servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); if (enableGzipCompression) { FilterHolder gzipFilter = new FilterHolder(GzipFilter.class); gzipFilter.setInitParameter("mimeTypes", "text/html,text/plain,text/css,text/javascript"); servletContext.addFilter(gzipFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); } if (enableRewriteFilter) { FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class); rewriteFilter.setInitParameter("confPath", "/urlrewrite.xml"); servletContext.addFilter(rewriteFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); } contexts.addHandler(servletContext); // enable request logging //if ("true".equals(configuration.getProperty("log.requests", "false"))) { if (logRequests) { String etcPath = basePath + "/etc"; File etcDir = new File(etcPath); if (!etcDir.exists()) { etcDir.mkdir(); } String logbackConfFilePath = basePath + "/etc/logback-access.xml"; File logbackConfFile = new File(logbackConfFilePath); if (!logbackConfFile.exists()) { // synthesize a logback accees log config file List<String> config = new LinkedList<String>(); config.add("<configuration>"); config.add(" <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">"); config.add(" <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">"); config.add(" <fileNamePattern>logs/" + logPrefix + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>"); config.add(" </rollingPolicy>"); config.add(" <encoder>"); config.add(" <charset>UTF-8</charset>"); config.add(" <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>"); config.add(" </encoder>"); config.add(" </appender>"); config.add(" <appender-ref ref=\"FILE\" />"); config.add("</configuration>"); logbackConfFile.createNewFile(); FileUtils.writeLines(logbackConfFile, "UTF-8", config); } FilterHolder loggingFilter = new FilterHolder(TeeFilter.class); servletContext.addFilter(loggingFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); loggingFilter.setInitParameter("includes", ""); RequestLogHandler requestLogHandler = new RequestLogHandler(); String logPath = basePath + "/logs"; File logDir = new File(logPath); // Create logs directory if not existing if (!logDir.exists()) { logDir.mkdir(); } RequestLogImpl requestLog = new RequestLogImpl(); requestLogHandler.setRequestLog(requestLog); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlers); } else { server.setHandler(contexts); } // add possible resource handler for static resources if (!resourceHandler.isEmpty()) { for (ContextHandler contextHandler : resourceHandler) { contexts.addHandler(contextHandler); } } //contexts.setHandlers(new Handler[] { new DefaultHandler(), contexts }); ResourceProvider resourceProviderInstance = resourceProvider.newInstance(); // configure JSON REST servlet JsonRestServlet structrRestServlet = new JsonRestServlet(resourceProviderInstance, defaultPropertyView, AbstractNode.uuid); ServletHolder structrRestServletHolder = new ServletHolder(structrRestServlet); servletParams.put("PropertyFormat", "FlatNameValue"); servletParams.put("Authenticator", authenticator.getName()); structrRestServletHolder.setInitParameters(servletParams); structrRestServletHolder.setInitOrder(0); // add to servlets servlets.put(restUrl + "/*", structrRestServletHolder); // add servlet elements int position = 1; for (Entry<String, ServletHolder> servlet : servlets.entrySet()) { String path = servlet.getKey(); ServletHolder servletHolder = servlet.getValue(); servletHolder.setInitOrder(position++); logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path }); servletContext.addServlet(servletHolder, path); } // register structr application context listener servletContext.addEventListener(new ApplicationContextListener()); contexts.addHandler(servletContext); //server.setHandler(contexts); // HTTPs can be disabled if (enableHttps) { if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) { // setup HTTP connector SslSelectChannelConnector httpsConnector = null; SslContextFactory factory = new SslContextFactory(keyStorePath); factory.setKeyStorePassword(keyStorePassword); httpsConnector = new SslSelectChannelConnector(factory); httpsConnector.setHost(host); httpsConnector.setPort(httpsPort); httpsConnector.setMaxIdleTime(maxIdleTime); httpsConnector.setRequestHeaderSize(requestHeaderSize); connectors.add(httpsConnector); } else { logger.log(Level.WARNING, "Unable to configure SSL, please make sure that application.https.port, application.keystore.path and application.keystore.password are set correctly in structr.conf."); } } if (host != null && !host.isEmpty() && restPort > -1) { SelectChannelConnector httpConnector = new SelectChannelConnector(); httpConnector.setHost(host); httpConnector.setPort(restPort); httpConnector.setMaxIdleTime(maxIdleTime); httpConnector.setRequestHeaderSize(requestHeaderSize); connectors.add(httpConnector); } else { logger.log(Level.WARNING, "Unable to configure REST port, please make sure that application.host, application.rest.port and application.rest.path are set correctly in structr.conf."); } if (!connectors.isEmpty()) { server.setConnectors(connectors.toArray(new Connector[0])); } else { logger.log(Level.SEVERE, "No connectors configured, aborting."); System.exit(0); } server.setGracefulShutdown(1000); server.setStopAtShutdown(true); if (!quiet) { System.out.println(); System.out.println("Starting " + applicationName + " (host=" + host + ":" + restPort + ", maxIdleTime=" + maxIdleTime + ", requestHeaderSize=" + requestHeaderSize + ")"); System.out.println("Base path " + basePath); System.out.println(); System.out.println(applicationName + " started: http://" + host + ":" + restPort + restUrl); System.out.println(); } server.start(); // The jsp directory is created by the container, but we don't need it removeDir(basePath, "jsp"); if (!callbacks.isEmpty()) { for (Callback callback : callbacks) { callback.execute(); } } if (waitForExit) { server.join(); if (!quiet) { System.out.println(); System.out.println(applicationName + " stopped."); System.out.println(); } } return server; }
From source file:org.structr.server.Structr.java
private void removeDir(final String basePath, final String directoryName) throws IOException { String strippedBasePath = StringUtils.stripEnd(basePath, "/"); File file = new File(strippedBasePath + "/" + directoryName); if (file.isDirectory()) { FileUtils.deleteDirectory(file); } else {/*from w ww . j a v a2 s .c o m*/ file.delete(); } }
From source file:org.trustedanalytics.uploader.rest.UploadException.java
@Override public String getMessage() { return Optional.ofNullable(getCause()).map(Throwable::getMessage) .map(msg -> StringUtils.stripEnd(msg, ".") + ".") .map(msg -> msg + " Following files has been successfully uploaded: ") .map(msg -> msg + files.stream().map(Transfer::getSource).collect(Collectors.joining(", ")) + ".") .orElse(getCause().getMessage()); }
From source file:org.xmen.xml.XMLNode.java
public List getAttributes() { List attrs = new ArrayList(); String content = null;// ww w . j a v a2 s . c o m int state = TAG; int start = -1; int startLength = 0; int endLength = 0; if (ITypeConstants.PI.equals(getType())) { startLength = 2; endLength = 2; } else if (ITypeConstants.DECL.equals(getType())) { // if ("!DOCTYPE".equals(getName())) // return getDoctypeAttributes(); startLength = 1; endLength = 1; } else if (ITypeConstants.TAG.equals(getType())) { startLength = 1; endLength = 1; } else if (ITypeConstants.EMPTYTAG.equals(getType())) { startLength = 1; endLength = 2; } else { return attrs; } try { content = document.get(getOffset(), getLength()); } catch (BadLocationException e) { UIPlugin.log(e); return attrs; } String name = getName(); int initial = name == null ? 0 : content.indexOf(name) + name.length(); for (int i = startLength + initial; i < content.length() - endLength; i++) { char c = content.charAt(i); switch (c) { case '"': if (state == DOUBLEQUOTE) { attrs.add(new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document)); start = -1; state = TAG; } else if (state == SINGLEQUOTE) { break; } else if (state != ATTR) { start = i; state = DOUBLEQUOTE; } else { state = DOUBLEQUOTE; } break; case '\'': if (state == SINGLEQUOTE) { attrs.add(new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document)); start = -1; state = TAG; } else if (state == DOUBLEQUOTE) { break; } else if (state != ATTR) { start = i; state = SINGLEQUOTE; } else { state = SINGLEQUOTE; } break; default: if (!Character.isWhitespace(c)) { if (state == TAG) { start = i; state = ATTR; } } else if (state == ATTR) { boolean stop = false; int j = i; // lookahead to see if this is an attribute name with no value for (; j < content.length() - endLength; j++) { char lookahead = content.charAt(j); switch (lookahead) { case '=': break; case '"': break; case '\'': break; default: stop = !Character.isWhitespace(lookahead); break; } if (stop) break; } if (stop) { attrs.add(new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document)); start = -1; state = TAG; } } } } if (start != -1) { attrs.add(new XMLNode(getOffset() + start, content.length() - startLength - start - (!getType().equals(ITypeConstants.TAG) ? 1 : 0), ITypeConstants.ATTR, document)); } for (Iterator iter = attrs.iterator(); iter.hasNext();) { XMLNode attr = (XMLNode) iter.next(); attr.length = StringUtils.stripEnd(attr.getContent(), null).length(); } return attrs; }
From source file:rapture.repo.cassandra.key.PathStripper.java
public static String stripPrefix(String prefix) { prefix = StringUtils.trimToEmpty(prefix); prefix = StringUtils.stripEnd(prefix, "/"); prefix = StringUtils.stripStart(prefix, "/"); if (StringUtils.isBlank(prefix)) { prefix = CassFolderHandler.DOLLAR_ROOT; }/* w ww .jav a 2 s. co m*/ return prefix; }
From source file:uk.gov.gchq.gaffer.example.util.JavaSourceUtil.java
public static String getRawJavaSnippet(final Class<?> clazz, final String modulePath, final String marker, final String start, final String end) { String javaCode = getRawJava(clazz.getName(), modulePath); final int markerIndex = javaCode.indexOf(marker); if (markerIndex > -1) { javaCode = javaCode.substring(markerIndex); javaCode = javaCode.substring(javaCode.indexOf(start) + start.length()); javaCode = javaCode.substring(0, javaCode.indexOf(end)); javaCode = StringUtils.stripEnd(javaCode, " " + NEW_LINE); // Remove indentation final String trimmedJavaCode = javaCode.trim(); final int leadingSpaces = javaCode.indexOf(trimmedJavaCode); if (leadingSpaces > 0) { final String spacesRegex = NEW_LINE + StringUtils.repeat(" ", leadingSpaces); javaCode = trimmedJavaCode.replace(spacesRegex, NEW_LINE); }//from ww w .j a v a2 s . c o m } else { javaCode = ""; } return javaCode; }