Java Code Examples for org.apache.commons.lang.StringUtils
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.
Source file: HCardExtractor.java

private void fixIncludes(HTMLDocument document,Node node,IssueReport report){ NamedNodeMap attributes=node.getAttributes(); if ("TD".equals(node.getNodeName()) && (null != attributes.getNamedItem("headers"))) { String id=attributes.getNamedItem("headers").getNodeValue(); Node header=document.findNodeById(id); if (null != header) { node.appendChild(header.cloneNode(true)); attributes.removeNamedItem("headers"); } } for ( Node current : DomUtils.findAllByAttributeName(document.getDocument(),"class")) { if (!DomUtils.hasClassName(current,"include")) continue; current.getAttributes().removeNamedItem("class"); ArrayList<TextField> res=new ArrayList<TextField>(); HTMLDocument.readUrlField(res,current); TextField id=res.get(0); if (null == id) continue; TextField refId=new TextField(StringUtils.substringAfter(id.value(),"#"),id.source()); Node included=document.findNodeById(refId.value()); if (null == included) continue; if (DomUtils.isAncestorOf(included,current)) { final int[] nodeLocation=DomUtils.getNodeLocation(current); report.notifyIssue(IssueReport.IssueLevel.Warning,"Current node tries to include an ancestor node.",nodeLocation[0],nodeLocation[1]); continue; } current.appendChild(included.cloneNode(true)); } }
Example 2
From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.
Source file: HdfsBrowser.java

@POST @Produces(MediaType.TEXT_PLAIN) @Timed public Response upload(final InputStream body,@QueryParam("path") final String outputPath,@QueryParam("overwrite") @DefaultValue("false") final boolean overwrite,@QueryParam("replication") @DefaultValue("3") final short replication,@QueryParam("blocksize") @DefaultValue("-1") long blocksize,@QueryParam("permission") @DefaultValue("u=rw,go=r") final String permission) throws IOException { if (outputPath == null) { return Response.status(Response.Status.BAD_REQUEST).header("Warning","199 " + "path cannot be null").cacheControl(cacheControl).build(); } if (blocksize == -1) { blocksize=config.getHadoopBlockSize(); } try { final URI path=hdfsWriter.write(body,outputPath,overwrite,replication,blocksize,permission); return Response.created(path).build(); } catch ( IOException e) { final String message; if (e.getMessage() != null) { message=StringUtils.split(e.getMessage(),'\n')[0]; } else { message=e.toString(); } log.warn("Unable to create [{}]: {}",outputPath,message); return Response.serverError().header("Warning","199 " + message).cacheControl(cacheControl).build(); } }
Example 3
From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/ajaxaware/.
Source file: AjaxAwareInterceptor.java

/** * <p> Executes the command wrapped in exception handler. </p> <p> Reacts to exceptions with 'Permission denied' type and try to reexecute the command in this situation. </p> <p> Prints the exception stack trace to help identify the problematic commands. </p> */ @Override public void intercept(final CommandContext ctx) throws CommandInterceptorException { long end=System.currentTimeMillis() + configuration.getTimeout(TimeoutType.AJAX); boolean exceptionLogged=false; while (System.currentTimeMillis() < end) { try { ctx.invoke(); return; } catch ( SeleniumException e) { final String message=StringUtils.defaultString(e.getMessage()); if (ArrayUtils.contains(PERMISSION_DENIED,message)) { System.err.println(message); if (!exceptionLogged) { exceptionLogged=true; System.err.println(ctx.toString()); e.printStackTrace(); } wait.waitForTimeout(); continue; } throw e; } } throw new PermissionDeniedException("Fails with 'Permission denied' errors when trying to execute jQuery"); }
Example 4
From project airlift, under directory /http-server/src/main/java/io/airlift/http/server/.
Source file: HashLoginServiceProvider.java

public HashLoginService get(){ String authConfig=config.getUserAuthFile(); try { if (!StringUtils.isEmpty(authConfig)) { HashLoginService service=new HashLoginService(HttpServerModule.REALM_NAME,authConfig); service.loadUsers(); return service; } return null; } catch ( IOException e) { log.error(e,"Error when loading user auth info from %s",authConfig); } return null; }
Example 5
From project archive-commons, under directory /archive-commons/src/main/java/org/archive/extract/.
Source file: JSONViewExtractorOutput.java

public void output(Resource resource) throws IOException { StreamCopy.readToEOF(resource.getInputStream()); List<List<String>> data=view.apply(resource.getMetaData().getTopMetaData()); if (data != null) { for ( List<String> d : data) { out.println(StringUtils.join(d,"\t")); } } }
Example 6
From project addis, under directory /application/src/main/java/org/drugis/addis/entities/analysis/.
Source file: NetworkBuilderFactory.java

@Override public String transform(TreatmentDefinition input){ List<String> names=new ArrayList<String>(); for ( Category category : input.getContents()) { names.add(getCleanName(category)); } return StringUtils.join(names,"_"); }
Example 7
From project Agot-Java, under directory /src/main/java/got/pojo/event/.
Source file: FamilyInfo.java

public String toString(){ String toStr=""; toStr+=String.format("FamilyName: %s\n",name); toStr+=String.format("Supply: %d\n",supply); toStr+=String.format("Power: %d\n",curPower); toStr+=String.format("Iron: %d\n",ironRank); toStr+=String.format("Blade: %d\n",bladeRank); toStr+=String.format("Raven: %d\n",ravenRank); toStr+=String.format("Territories: %s\n",StringUtils.join(conquerTerritories,",")); toStr+=String.format("Character: %s\n",battleCharacter); toStr+=String.format("Address: %s\n",address); return toStr; }
Example 8
From project alphaportal_dev, under directory /sys-src/alphaportal/core/src/main/java/alpha/portal/model/.
Source file: AlphaCard.java

/** * Constructor which takes the id of a case. * @param aCase Needs to be already saved (have an id). */ public AlphaCard(final AlphaCase aCase){ if (StringUtils.isEmpty(aCase.getCaseId())) throw new IllegalStateException("AlphaCard cannot be initialized with an unsaved case!"); this.setAlphaCardIdentifier(new AlphaCardIdentifier(aCase.getCaseId())); this.setAlphaCardDescriptor(new AlphaCardDescriptor(this)); this.setAlphaCase(aCase); }
Example 9
From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/.
Source file: CommandCompare.java

@Override public void validate() throws CommandValidationException { List<String> messages=constructMessages(); messages.add(validateInputFile("Pattern",getPatternFile())); messages.add(validateInputFile("Sample",getSampleFile())); messages.add(validateOutputFile("Output",output)); if (!messages.isEmpty()) { throw new CommandValidationException(StringUtils.join(messages,'\n')); } }
Example 10
From project ATHENA, under directory /core/apa/src/main/java/org/fracturedatlas/athena/apa/impl/jpa/.
Source file: DateTimeTicketProp.java

public void setValue(String s) throws InvalidValueException { if (s == null) { value=null; } else { try { setValue(DateUtil.parseDate(StringUtils.trim(s))); } catch ( Exception pe) { throw new InvalidValueException(buildExceptionMessage(s,propField),pe); } } }
Example 11
From project backup-plugin, under directory /src/main/java/org/jvnet/hudson/plugins/backup/.
Source file: BackupConfig.java

public String getFileNameTemplate(){ if (StringUtils.isNotEmpty(fileNameTemplate)) { return fileNameTemplate; } else { return DEFAULT_FILE_NAME_TEMPLATE; } }
Example 12
From project amplafi-sworddance, under directory /src/main/java/com/sworddance/beans/.
Source file: BeanWorker.java

/** * collects a chain of property methods that are called sequentially to get the final result. * @param clazz * @param propertyNamesList * @param readOnly only look for a getter * @return the chain of methods. */ protected List<PropertyAdaptor> getMethods(Class<?> clazz,String[] propertyNamesList,boolean readOnly){ Class<?>[] parameterTypes=new Class<?>[0]; List<PropertyAdaptor> propertyMethodChain=new ArrayList<PropertyAdaptor>(); for (Iterator<String> iter=Arrays.asList(propertyNamesList).iterator(); iter.hasNext(); ) { String propertyName=iter.next(); PropertyAdaptor propertyAdaptor=new PropertyAdaptor(propertyName); propertyAdaptor.setGetter(clazz,parameterTypes); if (!iter.hasNext() && !readOnly) { propertyAdaptor.initSetter(clazz); } if (propertyAdaptor.isExists()) { clazz=propertyAdaptor.getReturnType(); propertyMethodChain.add(propertyAdaptor); } else { throw new IllegalArgumentException(StringUtils.join(propertyNamesList) + " has bad property " + propertyName); } } return propertyMethodChain; }
Example 13
From project and-bible, under directory /AndBackendTest/src/net/bible/service/sword/.
Source file: SwordApiTest.java

public void testReadPilgrimKeys() throws Exception { Book book=getBook("Pilgrim"); Key globalKeyList=book.getGlobalKeyList(); System.out.println("Global key list"); for ( Key key : globalKeyList) { if (StringUtils.isNotEmpty(key.getName())) { String rawText=book.getRawText(key); System.out.println(key.getName() + " has " + rawText.length()+ " chars content"); if (rawText.length() < 30) { System.out.println(rawText); } } } assertEquals("Incorrect number of keys in master list",29,globalKeyList.getCardinality()); System.out.println("\nChildren"); for (int i=0; i < globalKeyList.getChildCount(); i++) { System.out.println(globalKeyList.get(i)); } assertEquals("Incorrect number of top level keys",6,globalKeyList.getChildCount()); }
Example 14
From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/commandline/.
Source file: RetrieveFile.java

private static String getTranslatedFilePath(File file,String localeString,String pathToStoreFile){ StringBuilder stringBuilder=new StringBuilder(pathToStoreFile); String locale=StringUtils.isNotBlank(localeString) ? localeString.replace(LOCALE_SEPERATOR,LOCALE_FILENAME_SEPERATOR) : StringUtils.EMPTY; stringBuilder.append(file.getName().replace(PROPERTY_FILE_EXT,LOCALE_FILENAME_SEPERATOR + locale + PROPERTY_FILE_EXT)); return stringBuilder.toString(); }
Example 15
From project aranea, under directory /server/src/main/java/no/dusken/aranea/web/spring/.
Source file: ChainedController.java

/** * Spawns multiple threads, one for each controller in the list of controllers, and within each thread, delegates to the controller's handleRequest() method. Once all the threads are complete, the ModelAndView objects returned from each of the handleRequest() methods are merged into a single view. The view name for the model is set to the specified view name. If an exception is thrown by any of the controllers in the chain, this exception is propagated up from the handleRequest() method of the ChainedController. * @param request the HttpServletRequest object. * @param response the HttpServletResponse object. * @return a merged ModelAndView object. * @throws Exception if one is thrown from the controllers in the chain. */ @SuppressWarnings("unchecked") private ModelAndView handleRequestParallely(HttpServletRequest request,HttpServletResponse response) throws Exception { ExecutorService service=Executors.newCachedThreadPool(); int numberOfControllers=controllers.size(); CallableController[] callables=new CallableController[numberOfControllers]; Future<ModelAndView>[] futures=new Future[numberOfControllers]; for (int i=0; i < numberOfControllers; i++) { callables[i]=new CallableController(controllers.get(i),request,response); futures[i]=service.submit(callables[i]); } ModelAndView mergedModel=new ModelAndView(); for ( Future<ModelAndView> future : futures) { ModelAndView model=future.get(); if (model != null) { mergedModel.addAllObjects(model.getModel()); } } if (StringUtils.isNotEmpty(this.viewName)) { mergedModel.setViewName(this.viewName); } return mergedModel; }
Example 16
From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/config/.
Source file: Config.java

public boolean equalsConfig(Config cmpConfig){ if (!StringUtils.equals(this.host,cmpConfig.host)) return false; if (!StringUtils.equals(this.eventType,cmpConfig.eventType)) return false; if (!StringUtils.equals(this.eventAttributeType,cmpConfig.eventAttributeType)) return false; if (!StringUtils.equals(this.monitoringTypesString,cmpConfig.monitoringTypesString)) return false; if (!StringUtils.equals(this.deployedEnv,cmpConfig.deployedEnv)) return false; if (!StringUtils.equals(this.deployedVersion,cmpConfig.deployedVersion)) return false; if (!StringUtils.equals(this.deployedType,cmpConfig.deployedType)) return false; if (!StringUtils.equals(this.deployedConfigSubPath,cmpConfig.deployedConfigSubPath)) return false; if (!this.pollingInterval.equals(cmpConfig.pollingInterval)) return false; return true; }
Example 17
From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/action/.
Source file: ActionableHelper.java

public static String getBuildUrl(AbstractBuild build){ String root=Hudson.getInstance().getRootUrl(); if (StringUtils.isBlank(root)) { return ""; } return root + build.getUrl(); }
Example 18
From project asadmin, under directory /asadmin-java/src/main/java/org/n0pe/asadmin/.
Source file: AsAdmin.java

public static String[] buildProcessParams(final IAsAdminCmd cmd,final IAsAdminConfig config) throws AsAdminException { final List<String> pbParams=new ArrayList<String>(); pbParams.add(ASADMIN_COMMAND_NAME); if (!Deployment.UNDEPLOY.equals(cmd.getActionCommand()) && !Deployment.DEPLOY.equals(cmd.getActionCommand()) && !"add-resources".equals(cmd.getActionCommand())) pbParams.add(cmd.getActionCommand()); if (!StringUtils.isEmpty(config.getHost()) && !Domain.START.equals(cmd.getActionCommand()) && !Domain.STOP.equals(cmd.getActionCommand())&& !Database.STOP.equals(cmd.getActionCommand())&& !Database.START.equals(cmd.getActionCommand())) { pbParams.add(HOST_OPT); pbParams.add(config.getHost()); } if (!StringUtils.isEmpty(config.getPort()) && !Domain.START.equals(cmd.getActionCommand()) && !Domain.STOP.equals(cmd.getActionCommand())&& !Database.STOP.equals(cmd.getActionCommand())&& !Database.START.equals(cmd.getActionCommand())) { pbParams.add(PORT_OPT); pbParams.add(config.getPort()); } if (config.isSecure()) { pbParams.add(SECURE_OPT); } if (cmd.needCredentials()) { pbParams.add(USER_OPT); pbParams.add(config.getUser()); pbParams.add(PASSWORDFILE_OPT); pbParams.add(cmd.handlePasswordFile(config.getPasswordFile())); } if (Deployment.UNDEPLOY.equals(cmd.getActionCommand()) || Deployment.DEPLOY.equals(cmd.getActionCommand()) || "add-resources".equals(cmd.getActionCommand())) pbParams.add(cmd.getActionCommand()); pbParams.addAll(Arrays.asList(cmd.getParameters())); return pbParams.toArray(new String[pbParams.size()]); }
Example 19
From project astyanax, under directory /src/main/java/com/netflix/astyanax/.
Source file: AstyanaxContext.java

public <T>AstyanaxContext<Keyspace> buildKeyspace(AstyanaxTypeFactory<T> factory){ ConnectionPool<T> cp=createConnectionPool(factory.createConnectionFactory(asConfig,cpConfig,tracerFactory,monitor)); this.cp=cp; final Keyspace keyspace=factory.createKeyspace(keyspaceName,cp,asConfig,tracerFactory); Supplier<Map<BigInteger,List<Host>>> supplier=null; switch (getNodeDiscoveryType()) { case DISCOVERY_SERVICE: Preconditions.checkNotNull(hostSupplier,"Missing host name supplier"); supplier=hostSupplier; break; case RING_DESCRIBE: supplier=new RingDescribeHostSupplier(keyspace,cpConfig.getPort()); break; case TOKEN_AWARE: if (hostSupplier == null) { supplier=new RingDescribeHostSupplier(keyspace,cpConfig.getPort()); } else { supplier=new FilteringHostSupplier(new RingDescribeHostSupplier(keyspace,cpConfig.getPort()),hostSupplier); } break; case NONE: supplier=null; break; } if (supplier != null) { discovery=new NodeDiscoveryImpl(StringUtils.join(Arrays.asList(clusterName,keyspaceName),"_"),asConfig.getDiscoveryDelayInSeconds() * 1000,supplier,cp); } return new AstyanaxContext<Keyspace>(this,keyspace); }
Example 20
From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/api/impl/.
Source file: ServletVelocityHelperImpl.java

@Override public SessionBean getSessionBean(final String sessionId){ if (StringUtils.isBlank(sessionId)) { return null; } Iterable<SessionBean> iterable=Iterables.filter(getAllSessionBeans(),new Predicate<SessionBean>(){ @Override public boolean apply( @Nullable SessionBean input){ return StringUtils.equals(sessionId,input.getSessionId()); } } ); return iterable.iterator().hasNext() ? iterable.iterator().next() : null; }
Example 21
From project autopatch, under directory /src/main/java/com/tacitknowledge/util/migration/jdbc/.
Source file: JdbcMigrationLauncherFactory.java

/** * Returns a list of MigrationListeners for the systemName specified in the properties. * @param systemName The name of the system to load MigrationListeners for. * @param properties The properties that has migration listeners specified. * @return A List of zero or more MigrationListeners * @throws MigrationException if unable to load listeners. */ protected List loadMigrationListeners(String systemName,Properties properties) throws MigrationException { try { List listeners=new ArrayList(); String[] listenerClassNames=null; String commaSeparatedList=properties.getProperty(systemName + ".listeners"); if (StringUtils.isNotBlank(commaSeparatedList)) { listenerClassNames=commaSeparatedList.split(","); for (Iterator it=Arrays.asList(listenerClassNames).iterator(); it.hasNext(); ) { String className=((String)it.next()).trim(); if (StringUtils.isNotBlank(className)) { Class c=Class.forName(className); MigrationListener listener=(MigrationListener)c.newInstance(); listener.initialize(systemName,properties); listeners.add(listener); } } } return listeners; } catch ( Exception e) { throw new MigrationException("Exception while loading migration listeners",e); } }
Example 22
From project azkaban, under directory /azkaban/src/java/azkaban/flow/.
Source file: GroupedFlow.java

@Override public String getName(){ return StringUtils.join(Iterables.transform(Arrays.asList(flows),new Function<Flow,String>(){ @Override public String apply( Flow flow){ return flow.getName(); } } ).iterator()," + "); }
Example 23
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/cron/.
Source file: Cron.java

/** * Parses the specified schedule into {@link #period execution period}. * @param schedule the specified schedule */ private void parse(final String schedule){ final int num=Integer.valueOf(StringUtils.substringBetween(schedule," "," ")); final String timeUnit=StringUtils.substringAfterLast(schedule," "); LOGGER.log(Level.FINEST,"Parsed cron job[schedule={0}]: [num={1}, timeUnit={2}]",new Object[]{schedule,num,timeUnit}); if ("hours".equals(timeUnit)) { period=num * SIXTY * SIXTY* THOUSAND; } else if ("minutes".equals(timeUnit)) { period=num * SIXTY * THOUSAND; } }
Example 24
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/event/ping/.
Source file: AddArticleGoogleBlogSearchPinger.java

@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject eventData=event.getData(); String articleTitle=null; try { final JSONObject article=eventData.getJSONObject(Article.ARTICLE); articleTitle=article.getString(Article.ARTICLE_TITLE); final JSONObject preference=PreferenceQueryService.getInstance().getPreference(); final String blogTitle=preference.getString(Preference.BLOG_TITLE); String blogHost=preference.getString(Preference.BLOG_HOST).toLowerCase().trim(); if ("localhost".equals(blogHost.split(":")[0].trim())) { LOGGER.log(Level.INFO,"Blog Solo runs on local server, so should not ping " + "Google Blog Search Service for the article[title={0}]",new Object[]{article.getString(Article.ARTICLE_TITLE)}); return; } blogHost=StringUtils.removeEnd("http://" + blogHost,"/"); final String articlePermalink=blogHost + article.getString(Article.ARTICLE_PERMALINK); final String spec="http://blogsearch.google.com/ping?name=" + URLEncoder.encode(blogTitle,"UTF-8") + "&url="+ URLEncoder.encode(blogHost,"UTF-8")+ "&changesURL="+ URLEncoder.encode(articlePermalink,"UTF-8"); LOGGER.log(Level.FINER,"Request Google Blog Search Service API[{0}] while adding an " + "article[title=" + articleTitle + "]",spec); final HTTPRequest request=new HTTPRequest(); request.setURL(new URL(spec)); URL_FETCH_SERVICE.fetchAsync(request); } catch ( final Exception e) { LOGGER.log(Level.SEVERE,"Ping Google Blog Search Service fail while adding an article[title=" + articleTitle + "]",e); } }