List of usage examples for org.apache.commons.lang3 StringUtils contains
public static boolean contains(final CharSequence seq, final CharSequence searchSeq)
Checks if CharSequence contains a search CharSequence, handling null .
From source file:de.mare.mobile.ui.jsf.pages.LoginPage.java
/** * Perform login of the user//from w ww . j a va2s .c o m * */ public String loginAction() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); try { request.login(this.username, this.password); String username = request.getUserPrincipal().getName(); User currentUser = userRepository.findUser(username); userSession.setUser(currentUser); LOG.info("username is: " + username); } catch (ServletException e) { if (StringUtils.contains(e.getMessage(), "User already logged in")) { String username = request.getUserPrincipal().getName(); User currentUser = userRepository.findUser(username); userSession.setUser(currentUser); LOG.info("User already loggedn in"); LOG.info("username is: " + username); } else { context.addMessage(null, new FacesMessage("Login failed.")); return "login.error"; } } return "portal.start"; }
From source file:com.sketchy.server.ImageUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {//from www . j ava2 s .c o m boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")) { uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)) { throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file SourceImageAttributes sourceImageAttributes = new SourceImageAttributes(); sourceImageAttributes.setImageName(uploadFileName); File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename()); if (pngFile.exists()) { throw new Exception( "Can not Upload file. File '" + uploadFileName + "' already exists!"); } File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename()); // Convert the image to a .PNG file BufferedImage image = ImageUtils.loadImage(fileItem.getInputStream()); ImageUtils.saveImage(pngFile, image); sourceImageAttributes.setWidth(image.getWidth()); sourceImageAttributes.setHeight(image.getHeight()); FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson()); jsonServletResult.put("imageName", uploadFileName); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:io.wcm.handler.media.MediaTest.java
@Test public void testToString() { assertTrue(StringUtils.contains(underTest.toString(), "/media/ref")); }
From source file:com.gargoylesoftware.htmlunit.WebResponseData.java
private InputStream getStream(final DownloadedContent downloadedContent, final List<NameValuePair> headers) throws IOException { InputStream stream = downloadedContent_.getInputStream(); if (stream == null) { return null; }//from www . j a v a 2 s . c o m if (downloadedContent.isEmpty()) { return stream; } final String encoding = getHeader(headers, "content-encoding"); if (encoding != null) { if (StringUtils.contains(encoding, "gzip")) { stream = new GZIPInputStream(stream); } else if (StringUtils.contains(encoding, "deflate")) { boolean zlibHeader = false; if (stream.markSupported()) { // should be always the case as the content is in a byte[] or in a file stream.mark(2); final byte[] buffer = new byte[2]; stream.read(buffer, 0, 2); zlibHeader = (((buffer[0] & 0xff) << 8) | (buffer[1] & 0xff)) == 0x789c; stream.reset(); } if (zlibHeader) { stream = new InflaterInputStream(stream); } else { stream = new InflaterInputStream(stream, new Inflater(true)); } } } return stream; }
From source file:keepinchecker.network.PacketSniffer.java
private void sendPacketsToDatabase(Map<Timestamp, Packet> packetMap) throws Exception { Set<KeepInCheckerPacket> objectionablePackets = new HashSet<>(); for (Map.Entry<Timestamp, Packet> entry : packetMap.entrySet()) { Timestamp packetTime = entry.getKey(); ZoneId currentTimezone = ZonedDateTime.now().getZone(); String packetString = PacketParser.convertToHumanReadableFormat(entry.getValue()); for (String objectionableWord : Constants.OBJECTIONABLE_WORDS) { if (StringUtils.contains(packetString, objectionableWord)) { KeepInCheckerPacket packet = new KeepInCheckerPacket(); packet.setTimestamp(packetTime.getTime()); packet.setTimezone(currentTimezone.getId()); String parsedGetValue = PacketParser.parse(PacketParser.GET, packetString); String parsedHostValue = PacketParser.parse(PacketParser.HOST, packetString); String parsedReferValue = PacketParser.parse(PacketParser.REFERER, packetString); packet.setGetValue(parsedGetValue.getBytes(StandardCharsets.UTF_8)); packet.setHostValue(parsedHostValue.getBytes(StandardCharsets.UTF_8)); packet.setRefererValue(parsedReferValue.getBytes(StandardCharsets.UTF_8)); if (!areGetHostAndRefererValuesEmpty(packet)) { objectionablePackets.add(packet); }// w w w.j a va2 s . c o m break; } } } if (!objectionablePackets.isEmpty()) { packetManager.savePackets(objectionablePackets); } }
From source file:com.cognifide.qa.bb.aem.core.sidepanel.internal.SidePanelImpl.java
private WebElement getResult(String asset) { return searchResults.stream() // .filter(element -> StringUtils.contains(element.getAttribute(HtmlTags.Attributes.DATA_PATH), asset)) // .findFirst() // .orElseThrow(() -> new IllegalStateException(asset + " asset was not found")); }
From source file:ch.cyberduck.core.openstack.SwiftAuthenticationService.java
public Set<? extends AuthenticationRequest> getRequest(final Host host, final LoginCallback prompt) throws LoginCanceledException { final Credentials credentials = host.getCredentials(); final StringBuilder url = new StringBuilder(); url.append(host.getProtocol().getScheme().toString()).append("://"); url.append(host.getHostname());/*from ww w . j av a 2 s.co m*/ if (!(host.getProtocol().getScheme().getPort() == host.getPort())) { url.append(":").append(host.getPort()); } final String context = PathNormalizer.normalize(host.getProtocol().getContext()); // Custom authentication context url.append(context); if (host.getProtocol().getDefaultHostname().endsWith("identity.api.rackspacecloud.com") || host.getHostname().endsWith("identity.api.rackspacecloud.com")) { return Collections.singleton(new Authentication20RAXUsernameKeyRequest(URI.create(url.toString()), credentials.getUsername(), credentials.getPassword(), null)); } final LoginOptions options = new LoginOptions(host.getProtocol()).password(false).anonymous(false) .publickey(false); if (context.contains("1.0")) { return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()), credentials.getUsername(), credentials.getPassword())); } else if (context.contains("1.1")) { return Collections.singleton(new Authentication11UsernameKeyRequest(URI.create(url.toString()), credentials.getUsername(), credentials.getPassword())); } else if (context.contains("2.0")) { // Prompt for tenant final String user; final String tenant; if (StringUtils.contains(credentials.getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':'); tenant = parts[0]; user = parts[1]; } else { user = credentials.getUsername(); tenant = prompt .prompt(host, credentials.getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Tenant Name", "Mosso"), options.usernamePlaceholder(LocaleFactory.localizedString("Tenant Name", "Mosso"))) .getUsername(); // Save tenant in username credentials.setUsername(String.format("%s:%s", tenant, credentials.getUsername())); } final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>(); requests.add(new Authentication20UsernamePasswordRequest(URI.create(url.toString()), user, credentials.getPassword(), tenant)); requests.add(new Authentication20UsernamePasswordTenantIdRequest(URI.create(url.toString()), user, credentials.getPassword(), tenant)); requests.add(new Authentication20AccessKeySecretKeyRequest(URI.create(url.toString()), user, credentials.getPassword(), tenant)); return requests; } else if (context.contains("3")) { // Prompt for project final String user; final String project; final String domain; if (StringUtils.contains(credentials.getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':'); if (parts.length == 3) { project = parts[0]; domain = parts[1]; user = parts[2]; } else { project = parts[0]; user = parts[1]; domain = prompt .prompt(host, credentials.getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Domain Name", "Mosso"), options.usernamePlaceholder( LocaleFactory.localizedString("Project Domain Name", "Mosso"))) .getUsername(); // Save project name and domain in username credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername())); } } else { user = credentials.getUsername(); final Credentials projectName = prompt.prompt(host, credentials.getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Name", "Mosso"), options.usernamePlaceholder(LocaleFactory.localizedString("Project Name", "Mosso"))); if (StringUtils.contains(credentials.getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(projectName.getUsername(), ':'); project = parts[0]; domain = parts[1]; } else { project = projectName.getUsername(); domain = prompt .prompt(host, credentials.getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Domain Name", "Mosso"), options.usernamePlaceholder( LocaleFactory.localizedString("Project Domain Name", "Mosso"))) .getUsername(); } // Save project name and domain in username credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername())); } final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>(); requests.add(new Authentication3UsernamePasswordProjectRequest(URI.create(url.toString()), user, credentials.getPassword(), project, domain)); return requests; } else { log.warn(String.format("Unknown context version in %s. Default to v1 authentication.", context)); // Default to 1.0 return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()), credentials.getUsername(), credentials.getPassword())); } }
From source file:com.sludev.commons.vfs2.provider.azure.AzFileObject.java
/** * Convenience method that returns the container and path from the current URL. * /* w ww.jav a 2s . com*/ * @return A tuple containing the container name and the path. */ protected Pair<String, String> getContainerAndPath() { Pair<String, String> res = null; try { URLFileName currName = (URLFileName) getName(); String currNameStr = currName.getPath(); currNameStr = StringUtils.stripStart(currNameStr, "/"); if (StringUtils.isBlank(currNameStr)) { log.warn(String.format("getContainerAndPath() : Path '%s' does not appear to be valid", currNameStr)); return null; } // Deal with the special case of the container root. if (StringUtils.contains(currNameStr, "/") == false) { // Container and root return new ImmutablePair<>(currNameStr, "/"); } String[] resArray = StringUtils.split(currNameStr, "/", 2); res = new ImmutablePair<>(resArray[0], resArray[1]); } catch (Exception ex) { log.error(String.format("getContainerAndPath() : Path does not appear to be valid"), ex); } return res; }
From source file:ch.cyberduck.core.b2.B2ErrorResponseInterceptor.java
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (StringUtils.contains(request.getRequestLine().getUri(), "b2_authorize_account")) { // Skip setting token for if (log.isDebugEnabled()) { log.debug("Skip setting token in b2_authorize_account"); }//from w ww . j a v a 2 s.c o m return; } switch (request.getRequestLine().getMethod()) { case "POST": // Do not override Authorization header for upload requests with upload URL token break; default: if (StringUtils.isNotBlank(authorizationToken)) { request.removeHeaders(HttpHeaders.AUTHORIZATION); request.addHeader(HttpHeaders.AUTHORIZATION, authorizationToken); } } }
From source file:com.anrisoftware.sscontrol.scripts.signrepo.SignRepo.java
private boolean checkRepo(Map<String, Object> args) throws Exception { Map<String, Object> taskargs = new HashMap<String, Object>(args); taskargs.put("outString", true); String name = args.get(NAME_KEY).toString(); String system = args.get(SYSTEM_KEY).toString(); String templateName = format("%s%s", "list", capitalize(system)); ProcessTask task = scriptExecFactory.create(taskargs, parent, threads, templateResource, templateName) .call();//from w ww.j a v a2s .c o m for (String string : split(task.getOut(), "\n")) { if (StringUtils.contains(string, name)) { return true; } } return false; }