List of usage examples for org.apache.commons.lang3 StringUtils removeEnd
public static String removeEnd(final String str, final String remove)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null .
From source file:de.blizzy.documentr.web.system.SystemController.java
@RequestMapping(value = "/save", method = RequestMethod.POST) @PreAuthorize("hasApplicationPermission(ADMIN)") public String saveSettings(@ModelAttribute @Valid SystemSettingsForm form, BindingResult bindingResult, Authentication authentication) throws IOException { if (bindingResult.hasErrors()) { return "/system/edit"; //$NON-NLS-1$ }//from ww w .j a va 2 s . co m User user = userStore.getUser(authentication.getName()); Map<String, String> settings = Maps.newHashMap(); String documentrHost = form.getDocumentrHost(); // remove trailing slash documentrHost = StringUtils.removeEnd(documentrHost, "/"); //$NON-NLS-1$ settings.put(SystemSettingsStore.DOCUMENTR_HOST, documentrHost); settings.put(SystemSettingsStore.SITE_NOTICE, form.getSiteNotice()); settings.put(SystemSettingsStore.MAIL_HOST_NAME, form.getMailHostName()); settings.put(SystemSettingsStore.MAIL_HOST_PORT, String.valueOf(form.getMailHostPort())); settings.put(SystemSettingsStore.MAIL_SENDER_EMAIL, form.getMailSenderEmail()); settings.put(SystemSettingsStore.MAIL_SENDER_NAME, form.getMailSenderName()); settings.put(SystemSettingsStore.MAIL_SUBJECT_PREFIX, form.getMailSubjectPrefix()); settings.put(SystemSettingsStore.MAIL_DEFAULT_LANGUAGE, form.getMailDefaultLanguage()); settings.put(SystemSettingsStore.BCRYPT_ROUNDS, String.valueOf(form.getBcryptRounds())); settings.put(SystemSettingsStore.PAGE_FOOTER_HTML, form.getPageFooterHtml()); settings.put(SystemSettingsStore.UPDATE_CHECK_INTERVAL, form.getUpdateCheckInterval()); systemSettingsStore.saveSettings(settings, user); for (Map.Entry<String, SortedMap<String, String>> entry : form.getMacroSettings().entrySet()) { systemSettingsStore.setMacroSetting(entry.getKey(), entry.getValue(), user); } return "redirect:/system/edit"; //$NON-NLS-1$ }
From source file:com.norconex.collector.http.robot.impl.StandardRobotsTxtProvider.java
private RobotData.Precision matchesUserAgent(String userAgent, String value) { if ("*".equals(value)) { return RobotData.Precision.WILD; }/* w w w . ja va2 s .c om*/ if (StringUtils.equalsIgnoreCase(userAgent, value)) { return RobotData.Precision.EXACT; } if (value.endsWith("*")) { String val = StringUtils.removeEnd(value, "*"); if (StringUtils.startsWithIgnoreCase(userAgent, val)) { return RobotData.Precision.PARTIAL; } } if (StringUtils.containsIgnoreCase(userAgent, value)) { return RobotData.Precision.PARTIAL; } return RobotData.Precision.NOMATCH; }
From source file:com.norconex.collector.http.crawler.AbstractHttpTest.java
protected List<HttpDocument> getCommitedDocuments(HttpCrawler crawler) throws IOException { File addDir = getCommitterAddDir(crawler); Collection<File> files = FileUtils.listFiles(addDir, null, true); List<HttpDocument> docs = new ArrayList<>(); for (File file : files) { if (file.isDirectory() || !file.getName().endsWith(FileSystemCommitter.EXTENSION_CONTENT)) { continue; }//w w w. j a va 2 s.co m HttpMetadata meta = new HttpMetadata(file.getAbsolutePath()); String basePath = StringUtils.removeEnd(file.getAbsolutePath(), FileSystemCommitter.EXTENSION_CONTENT); meta.load(FileUtils.openInputStream(new File(basePath + ".meta"))); String reference = FileUtils.readFileToString(new File(basePath + ".ref")); HttpDocument doc = new HttpDocument(reference, crawler.getStreamFactory().newInputStream(file)); // remove previous reference to avoid duplicates doc.getMetadata().remove(HttpMetadata.COLLECTOR_URL); doc.getMetadata().load(meta); docs.add(doc); } return docs; }
From source file:ch.cyberduck.core.sftp.SFTPChallengeResponseAuthentication.java
public boolean authenticate(final Host host, final Credentials credentials, final LoginCallback controller) throws BackgroundException { if (StringUtils.isBlank(host.getCredentials().getPassword())) { return false; }/*from ww w .j av a 2 s. co m*/ if (log.isDebugEnabled()) { log.debug(String.format("Login using challenge response authentication with credentials %s", credentials)); } try { session.getClient().auth(credentials.getUsername(), new AuthKeyboardInteractive(new ChallengeResponseProvider() { /** * Password sent flag */ private final AtomicBoolean password = new AtomicBoolean(); private String name = StringUtils.EMPTY; private String instruction = StringUtils.EMPTY; @Override public List<String> getSubmethods() { return Collections.emptyList(); } @Override public void init(final Resource resource, final String name, final String instruction) { if (StringUtils.isNoneBlank(instruction)) { this.instruction = instruction; } if (StringUtils.isNoneBlank(name)) { this.name = name; } } @Override public char[] getResponse(final String prompt, final boolean echo) { if (log.isDebugEnabled()) { log.debug(String.format("Reply to challenge name %s with instruction %s", name, instruction)); } final String response; // For each prompt, the corresponding echo field indicates whether the user input should // be echoed as characters are typed if (!password.get() // Some servers ask for one-time passcode first && !StringUtils.contains(prompt, "Verification code")) { // In its first callback the server prompts for the password if (log.isDebugEnabled()) { log.debug("First callback returning provided credentials"); } response = credentials.getPassword(); password.set(true); } else { final StringAppender message = new StringAppender().append(instruction) .append(prompt); // Properly handle an instruction field with embedded newlines. They should also // be able to display at least 30 characters for the name and prompts. final Credentials additional = new Credentials(credentials.getUsername()) { @Override public String getPasswordPlaceholder() { return StringUtils.removeEnd(StringUtils.strip(prompt), ":"); } }; try { final StringAppender title = new StringAppender().append(name).append( LocaleFactory.localizedString("Provide additional login credentials", "Credentials")); controller.prompt(host, additional, title.toString(), message.toString(), new LoginOptions().user(false).keychain(false)); } catch (LoginCanceledException e) { return EMPTY_RESPONSE; } response = additional.getPassword(); } // Responses are encoded in ISO-10646 UTF-8. return response.toCharArray(); } @Override public boolean shouldRetry() { return false; } })); } catch (IOException e) { throw new SFTPExceptionMappingService().map(e); } return session.getClient().isAuthenticated(); }
From source file:com.mirth.connect.server.migration.Migrator.java
protected List<String> readStatements(String scriptResourceName, Map<String, Object> replacements) throws IOException { List<String> script = new ArrayList<String>(); Scanner scanner = null;/*www. j a v a 2 s. c o m*/ if (scriptResourceName.charAt(0) != '/' && defaultScriptPath != null) { scriptResourceName = defaultScriptPath + "/" + scriptResourceName; } try { scanner = new Scanner(IOUtils.toString(ResourceUtil.getResourceStream(getClass(), scriptResourceName))); while (scanner.hasNextLine()) { StringBuilder stringBuilder = new StringBuilder(); boolean blankLine = false; while (scanner.hasNextLine() && !blankLine) { String temp = scanner.nextLine(); if (temp.trim().length() > 0) { stringBuilder.append(temp + " "); } else { blankLine = true; } } // Trim ending semicolons so Oracle doesn't throw // "java.sql.SQLException: ORA-00911: invalid character" String statementString = StringUtils.removeEnd(stringBuilder.toString().trim(), ";"); if (statementString.length() > 0) { if (replacements != null && !replacements.isEmpty()) { for (String key : replacements.keySet()) { statementString = StringUtils.replace(statementString, "${" + key + "}", replacements.get(key).toString()); } } script.add(statementString); } } return script; } finally { if (scanner != null) { scanner.close(); } } }
From source file:com.oembedler.moon.graphql.engine.GraphQLQueryTemplate.java
protected String expandNestedObjectTree(String nodeName, GraphQLObjectType graphQLOutputType) { StringBuilder stringBuilder = new StringBuilder(); for (GraphQLFieldDefinition graphQLFieldDefinition : graphQLOutputType.getFieldDefinitions()) { GraphQLUnmodifiedType graphQLUnmodifiedType = schemaUtil .getUnmodifiedType(graphQLFieldDefinition.getType()); if (graphQLUnmodifiedType instanceof GraphQLScalarType) stringBuilder.append(graphQLFieldDefinition.getName() + ", "); else {/*from ww w.ja v a2s .co m*/ GraphQLObjectType castedGraphQLObjectType = (GraphQLObjectType) graphQLUnmodifiedType; stringBuilder .append(expandNestedObjectTree(graphQLFieldDefinition.getName(), castedGraphQLObjectType)); } } String result = StringUtils.removeEnd(stringBuilder.toString(), ", "); return StringUtils.isNoneBlank(result) ? String.format("%s { %s }", nodeName, result) : ""; }
From source file:com.neophob.sematrix.listener.TcpServer.java
/** * tcp server thread./*from w w w . ja v a 2 s . c om*/ */ public void run() { LOG.log(Level.INFO, "Ready receiving messages..."); while (Thread.currentThread() == runner) { if (tcpServer != null) { try { //check if client is available if (client != null && client.active()) { //do not send sound status to gui - very cpu intensive! //sendSoundStatus(); if ((count % 20) == 2 && Collector.getInstance().isRandomMode()) { sendStatusToGui(); } } Client c = tcpServer.available(); if (c != null && c.available() > 0) { //clean message String msg = lastMsg + StringUtils.replace(c.readString(), "\n", ""); //add replacement end string msg = StringUtils.replace(msg, FUDI_ALTERNATIVE_END_MARKER, FUDI_MSG_END_MARKER); msg = StringUtils.trim(msg); int msgCount = StringUtils.countMatches(msg, FUDI_MSG_END_MARKER); LOG.log(Level.INFO, "Got Message: {0} cnt: {1}", new Object[] { msg, msgCount }); //work around bug - the puredata gui sends back a message as soon we send one long delta = System.currentTimeMillis() - lastMessageSentTimestamp; if (delta < FLOODING_TIME) { LOG.log(Level.INFO, "Ignore message, flooding protection ({0}<{1})", new String[] { "" + delta, "" + FLOODING_TIME }); //delete message msgCount = 0; msg = ""; } //ideal, one message receieved if (msgCount == 1) { msg = StringUtils.removeEnd(msg, FUDI_MSG_END_MARKER); lastMsg = ""; processMessage(StringUtils.split(msg, ' ')); } else if (msgCount == 0) { //missing end of message... save it lastMsg = msg; } else { //more than one message receieved, split it //TODO: reuse partial messages lastMsg = ""; String[] msgs = msg.split(FUDI_MSG_END_MARKER); for (String s : msgs) { s = StringUtils.trim(s); s = StringUtils.removeEnd(s, FUDI_MSG_END_MARKER); processMessage(StringUtils.split(s, ' ')); } } } } catch (Exception e) { } } count++; try { Thread.sleep(50); } catch (InterruptedException e) { //Ignored } } }
From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java
/** * Maps all requests to NodeJS binaries simulating a Maven 2 directory structure. *///from w w w.j a v a2 s . co m @GET @Path("{groupIdPath:[a-zA-Z0-9\\-\\_]+(/[a-zA-Z0-9\\-\\_]+)*}" + "/{artifactId:[a-zA-Z0-9\\-\\_\\.]+}" + "/{version:\\d+(\\.\\d+)*}" + "/{artifactIdFilename:[a-zA-Z0-9\\-\\_\\.]+}" + "-{versionFilename:\\d+(\\.\\d+)*}" + "-{os:[a-zA-Z0-9\\_]+}" + "-{arch:[a-zA-Z0-9\\_]+}" + ".{type:[a-z]+(\\.[a-z]+)*(\\.sha1)?}") @Timed public Response getBinary(@PathParam("groupIdPath") String groupIdPath, @PathParam("artifactId") String artifactId, @PathParam("version") String version, @PathParam("artifactIdFilename") String artifactIdFilename, @PathParam("versionFilename") String versionFilename, @PathParam("os") String os, @PathParam("arch") String arch, @PathParam("type") String type) throws IOException { String groupId = mapGroupId(groupIdPath); if (!validateBasicParams(groupId, artifactId, version, artifactIdFilename, versionFilename)) { return Response.status(Response.Status.NOT_FOUND).build(); } ArtifactType artifactType = getArtifactType(artifactId); if (artifactType != ArtifactType.NODEJS) { return Response.status(Response.Status.NOT_FOUND).build(); } boolean getChecksum = false; if (StringUtils.endsWith(type, ".sha1")) { getChecksum = true; } String url = buildBinaryUrl(artifactType, version, os, arch, StringUtils.removeEnd(type, ".sha1")); return getBinaryWithChecksumValidation(url, version, getChecksum); }
From source file:net.sf.dynamicreports.jasper.base.JasperCustomValues.java
@Override public String toString() { StringBuilder result = new StringBuilder(); for (String name : valueTypes.keySet()) { result.append(valueTypes.get(name).name() + ":" + name); result.append(", "); }// ww w . j a v a2 s .c om return "{" + StringUtils.removeEnd(result.toString(), ", ") + "}"; }
From source file:com.norconex.collector.http.robot.impl.StandardRobotsTxtProvider.java
private String getBaseURL(String url) { String baseURL = url.replaceFirst("(.*?://.*?/)(.*)", "$1"); if (baseURL.endsWith("/")) { baseURL = StringUtils.removeEnd(baseURL, "/"); }/* w ww . jav a 2 s .c o m*/ return baseURL; }