List of usage examples for org.apache.commons.lang3 StringUtils trimToNull
public static String trimToNull(final String str)
Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null .
From source file:com.jayway.restassured.path.json.config.JsonPathConfig.java
private JsonPathConfig(NumberReturnType numberReturnType, JsonParserType parserType, GsonObjectMapperFactory gsonObjectMapperFactory, Jackson1ObjectMapperFactory jackson1ObjectMapperFactory, Jackson2ObjectMapperFactory jackson2ObjectMapperFactory, JsonPathObjectDeserializer defaultDeserializer, String charset) {/*www .j av a 2 s .c o m*/ if (numberReturnType == null) throw new IllegalArgumentException("numberReturnType cannot be null"); charset = StringUtils.trimToNull(charset); if (charset == null) throw new IllegalArgumentException("Charset cannot be empty"); this.charset = charset; this.numberReturnType = numberReturnType; this.defaultDeserializer = defaultDeserializer; this.defaultParserType = parserType; this.gsonObjectMapperFactory = gsonObjectMapperFactory; this.jackson1ObjectMapperFactory = jackson1ObjectMapperFactory; this.jackson2ObjectMapperFactory = jackson2ObjectMapperFactory; }
From source file:com.norconex.collector.http.url.impl.GenericCanonicalLinkDetector.java
@Override public String detectFromMetadata(String reference, HttpMetadata metadata) { String link = StringUtils.trimToNull(metadata.getString("Link")); if (link != null) { if (link.toLowerCase().matches(".*rel\\s*=\\s*[\"']canonical[\"'].*")) { link = StringUtils.substringBetween(link, "<", ">"); return toAbsolute(reference, link); }//from w w w . ja v a 2s.c o m } return null; }
From source file:at.bitfire.davdroid.ui.CreateCalendarActivity.java
public void onCreateCollection(MenuItem item) { boolean ok = true; CollectionInfo info = new CollectionInfo(); Spinner spinner = (Spinner) findViewById(R.id.home_sets); String homeSet = (String) spinner.getSelectedItem(); EditText edit = (EditText) findViewById(R.id.display_name); info.displayName = edit.getText().toString(); if (TextUtils.isEmpty(info.displayName)) { edit.setError(getString(R.string.create_collection_display_name_required)); ok = false;//from w ww . j a v a2s .c o m } edit = (EditText) findViewById(R.id.description); info.description = StringUtils.trimToNull(edit.getText().toString()); View view = findViewById(R.id.color); info.color = ((ColorDrawable) view.getBackground()).getColor(); spinner = (Spinner) findViewById(R.id.time_zone); net.fortuna.ical4j.model.TimeZone tz = DateUtils.tzRegistry.getTimeZone((String) spinner.getSelectedItem()); if (tz != null) { Calendar cal = new Calendar(); cal.getComponents().add(tz.getVTimeZone()); info.timeZone = cal.toString(); } RadioGroup typeGroup = (RadioGroup) findViewById(R.id.type); switch (typeGroup.getCheckedRadioButtonId()) { case R.id.type_events: info.supportsVEVENT = true; break; case R.id.type_tasks: info.supportsVTODO = true; break; case R.id.type_events_and_tasks: info.supportsVEVENT = true; info.supportsVTODO = true; break; } if (ok) { info.type = CollectionInfo.Type.CALENDAR; info.url = HttpUrl.parse(homeSet).resolve(UUID.randomUUID().toString() + "/").toString(); CreateCollectionFragment.newInstance(account, info).show(getSupportFragmentManager(), null); } }
From source file:hoot.services.controllers.job.ProcessJobRunnable.java
private void processCommand() throws Exception { logger.debug("Processing job: {}", jobId); jobStatusManager.addJob(jobId);//from w ww . jav a 2 s . com JSONObject command = null; try { JSONParser parser = new JSONParser(); command = (JSONObject) parser.parse(params); //log.debug(JsonUtils.objectToJson(command)); JSONObject result = processJob(jobId, command); //log.debug(JsonUtils.objectToJson(result)); String warnings = null; Object oWarn = result.get("warnings"); if (oWarn != null) { warnings = oWarn.toString(); } String statusDetail = ""; if (warnings != null) { statusDetail += "WARNINGS: " + warnings; } Map<String, String> params = paramsToMap(command); if (params.containsKey("writeStdOutToStatusDetail") && Boolean.parseBoolean(params.get("writeStdOutToStatusDetail"))) { statusDetail += "INFO: " + result.get("stdout"); } if (StringUtils.trimToNull(statusDetail) != null) { jobStatusManager.setComplete(jobId, statusDetail); } else { jobStatusManager.setComplete(jobId); } } catch (Exception e) { jobStatusManager.setFailed(jobId, e.getMessage()); throw e; } finally { logger.debug("End process Job: {}", jobId); } }
From source file:alfio.controller.api.user.RestEventApiController.java
@RequestMapping("events/{shortName}") public ResponseEntity<PublicEvent> showEvent(@PathVariable("shortName") String shortName, @RequestParam(value = "specialCode", required = false) String specialCodeParam, HttpServletRequest request) {// w w w.ja v a 2 s.c om Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(specialCodeParam)) .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode)); return eventRepository.findOptionalByShortName(shortName).map((e) -> { List<PublicCategory> categories = ticketCategoryRepository.findAllTicketCategories(e.getId()).stream() .filter((c) -> !c.isAccessRestricted() || (specialCode.filter(sc -> sc.getTicketCategoryId() == c.getId()).isPresent())) .map(c -> buildPublicCategory(c, e)).collect(Collectors.toList()); Organization organization = organizationRepository.getById(e.getOrganizationId()); return new ResponseEntity<>(new PublicEvent(e, request.getContextPath(), descriptionsLoader.eventDescriptions(), categories, organization), HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
From source file:hoot.services.controllers.wps.MarkItemsReviewedProcessletTest.java
private MarkItemsReviewedResponse execMark(final String mapId, final String markAll, final MarkItemsReviewedRequest markItemsReviewedRequest) throws Exception { MarkItemsReviewedProcesslet processlet = new MarkItemsReviewedProcesslet(); LinkedList<ProcessletInput> allInputs = new LinkedList<ProcessletInput>(); if (mapId != null) { //default data type for a wps input is string, so no extra params needed here for mapId allInputs.add(WpsUtils.createLiteralInput("mapId", String.valueOf(mapId))); }/*from www. ja v a 2 s . co m*/ if (StringUtils.trimToNull(markAll) != null) { allInputs.add(WpsUtils.createLiteralInput("markAll", String.valueOf(markAll))); } if (markItemsReviewedRequest.getReviewedItems() != null) { LiteralInputDefinition inputParamDef = new LiteralInputDefinition(); LiteralInputDefinition.DataType dataType = new LiteralInputDefinition.DataType(); inputParamDef.setMinOccurs(new BigInteger("0")); inputParamDef.setMaxOccurs(new BigInteger("1")); dataType.setReference("http://www.w3.org/TR/xmlschema-2/#string"); inputParamDef.setDataType(dataType); allInputs.add(WpsUtils.createLiteralInput("reviewedItems", JsonUtils.objectToJson(markItemsReviewedRequest.getReviewedItems()), inputParamDef)); } if (markItemsReviewedRequest.getReviewedItemsChangeset() != null) { LiteralInputDefinition inputParamDef = new LiteralInputDefinition(); LiteralInputDefinition.DataType dataType = new LiteralInputDefinition.DataType(); inputParamDef.setMinOccurs(new BigInteger("0")); inputParamDef.setMaxOccurs(new BigInteger("1")); dataType.setReference("http://www.w3.org/TR/xmlschema-2/#string"); inputParamDef.setDataType(dataType); allInputs.add(WpsUtils.createLiteralInput("reviewedItemsChangeset", markItemsReviewedRequest.getReviewedItemsChangeset(), inputParamDef)); } ProcessletInputs in = new ProcessletInputs(allInputs); ProcessDefinition def = new ProcessDefinition(); def.setOutputParameters(new OutputParameters()); LinkedList<ProcessletOutput> allOutputs = new LinkedList<ProcessletOutput>(); allOutputs.add(WpsUtils.createLiteralOutput("changesetUploadResponse")); allOutputs.add(WpsUtils.createLiteralOutput("numItemsMarkedReviewed")); allOutputs.add(WpsUtils.createLiteralOutput("changesetId")); final ProcessletOutputs out = new ProcessletOutputs(def, allOutputs); processlet.process(in, out, new ProcessExecution(null, null, null, null, out)); MarkItemsReviewedResponse response = new MarkItemsReviewedResponse(); response.setChangesetId(Long.parseLong(((LiteralOutputImpl) out.getParameter("changesetId")).getValue())); response.setChangesetUploadResponse( ((LiteralOutputImpl) out.getParameter("changesetUploadResponse")).getValue()); response.setNumItemsMarkedReviewed( Integer.parseInt(((LiteralOutputImpl) out.getParameter("numItemsMarkedReviewed")).getValue())); return response; }
From source file:com.stratio.ingestion.sink.cassandra.CassandraSink.java
@Override public void configure(Context context) { contactPoints = new ArrayList<InetSocketAddress>(); final String hosts = context.getString(CONF_HOSTS, DEFAULT_HOST); for (final String host : Splitter.on(',').split(hosts)) { try {//from w w w . j a v a 2s.c o m final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(DEFAULT_PORT); contactPoints.add(new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort())); } catch (IllegalArgumentException ex) { throw new ConfigurationException("Could not parse host: " + host, ex); } } this.username = context.getString(CONF_USERNAME); this.password = context.getString(CONF_PASSWORD); this.consistency = context.getString(CONF_CONSISTENCY_LEVEL, DEFAULT_CONSISTENCY_LEVEL); this.bodyColumn = context.getString(CONF_BODY_COLUMN, DEFAULT_BODY_COLUMN); final String tablesString = StringUtils.trimToNull(context.getString(CONF_TABLES)); if (tablesString == null) { throw new ConfigurationException(String.format("%s is mandatory", CONF_TABLES)); } this.tableStrings = Arrays.asList(tablesString.split(",")); final String cqlFile = StringUtils.trimToNull(context.getString(CONF_CQL_FILE)); if (cqlFile != null) { try { this.initCql = IOUtils.toString(new FileInputStream(cqlFile)); } catch (IOException ex) { throw new ConfigurationException("Cannot read CQL file: " + cqlFile, ex); } } this.batchSize = context.getInteger(CONF_BATCH_SIZE, DEFAULT_BATCH_SIZE); this.sinkCounter = new SinkCounter(this.getName()); }
From source file:com.olegchir.flussonic_userlinks.wicket.IncludeResolver.IncludeResolver.java
/** * Handles resolving the wicket:include tag. If a filename is specified this * file will be looked up. If a key is specified it's value is looked up * using the resource mechanism. The looked up value will then be used as * filename./*from w ww . j a va 2 s .c om*/ * */ public Component resolve(MarkupContainer container, MarkupStream markupStream, ComponentTag tag) { if ((tag instanceof WicketTag) && tagname.equalsIgnoreCase(tag.getName())) { WicketTag wtag = (WicketTag) tag; String fileName = StringUtils.trimToNull(wtag.getAttribute("file")); String fileKey = StringUtils.trimToNull(wtag.getAttribute("key")); if (null != fileKey) { if (null != fileName) { throw new MarkupException("Wrong format of: you must not use file and key attribtue at once"); } fileName = StringUtils.trimToNull(container.getString(fileKey)); if (null == fileName) { throw new MarkupException("The key inside could not be resolved"); } } else if (null == fileName) { throw new MarkupException("Wrong format of: specify the file or key attribute"); } final String id = "_" + tagname + "_" + container.getPage().getAutoIndex(); IncludeContainer ic = new IncludeContainer(id, fileName, fileKey, markupStream); ic.setRenderBodyOnly(container.getApplication().getMarkupSettings().getStripWicketTags()); // container.autoAdd(ic, markupStream); return ic; } return null; }
From source file:hoot.services.review.ReviewItemsMarker.java
/** * Uploads an OSM changeset with items marked as reviewed to the services database and then parses * the contents of the changeset, marking items as reviewed based on custom hoot review tags it * contains//ww w.j av a 2s . c o m * * @param markItemsReviewedRequest a request to mark items as reviewed which contains an * object describing the items to be reviewed, as well as an optional OSM xml changeset; the two * sets of data are not cross validated with each other in any way * @param markAll an option to mark all data for the map layer as reviewed; when true, the * reviewed items object is no needed and ignored if populated * @return an mark items as reviewed response * @throws Exception */ public MarkItemsReviewedResponse markItemsReviewed(final MarkItemsReviewedRequest markItemsReviewedRequest, final boolean markAll) throws Exception { MarkItemsReviewedResponse markItemsReviewedResponse = new MarkItemsReviewedResponse(); Document changesetUploadResponse = null; long changesetId = -1; if (StringUtils.trimToNull(markItemsReviewedRequest.getReviewedItemsChangeset()) != null) { boolean changesetHasElements = false; final Document changesetDiffDoc = XmlDocumentBuilder .parse(markItemsReviewedRequest.getReviewedItemsChangeset()); changesetHasElements = ChangesetUploadXmlValidator.changesetHasElements(changesetDiffDoc); if (changesetHasElements) { changesetId = Changeset.createChangeset( Changeset.getChangesetCreateDoc("marking items reviewed for map ID: " + mapId), mapId, userId, conn); //TODO: There really needs to also be a check in here that makes sure every element tag //already has a changeset attribute (or iterate through the element tag DOM attributes. //For now, just assuming that iD has already added the changeset attributes. Whether the //value is empty or not doesn't matter, since it will be overwritten here. markItemsReviewedRequest .setReviewedItemsChangeset(markItemsReviewedRequest.getReviewedItemsChangeset() .replaceAll("changeset=\"\"", "changeset=\"" + changesetId + "\"") .replaceAll("changeset=\"\\d+\"", "changeset=\"" + changesetId + "\"")); //the changeset upload process will catch any elements in the changeset xml which are out //of sync with the element versions in the OSM element tables, by design changesetUploadResponse = (new ChangesetDbWriter(conn)).write(mapId, changesetId, markItemsReviewedRequest.getReviewedItemsChangeset()); Changeset.closeChangeset(mapId, changesetId, conn); markItemsReviewedResponse .setChangesetUploadResponse(XmlDocumentBuilder.toString(changesetUploadResponse)); } } //mark all items as reviewed in review_items; record the changeset ID and other review //details if (markAll) { markItemsReviewedRequest .setReviewedItems(ReviewUtils.getReviewedItemsCollectionForAllRecords(mapId, conn)); } final int numItemsMarkedReviewed = (new ReviewedItemsWriter(conn, mapId, changesetId)) .writeReviewedItems(markItemsReviewedRequest.getReviewedItems()); //this will still be = -1 at this point if nothing was in the changeset input parameter or it //was invalid markItemsReviewedResponse.setChangesetId(changesetId); //this will null at this point if nothing was in the changeset input parameter or it was invalid markItemsReviewedResponse.setNumItemsMarkedReviewed(numItemsMarkedReviewed); return markItemsReviewedResponse; }
From source file:hoot.services.controllers.info.AboutResourceTest.java
@Test @Category(UnitTest.class) public void getServicesVersionDetail() throws IOException { Properties hootProps = HootProperties.getInstance(); hootProps.clear();/* w w w . ja v a 2s .co m*/ hootProps.setProperty("testProp1", "testVal1"); HootProperties.setProperties(hootProps); mockBuildInfo(); ServicesDetail responseData = null; try { responseData = resource().path("/about/servicesVersionDetail").accept(MediaType.APPLICATION_JSON) .get(ServicesDetail.class); } catch (UniformInterfaceException e) { ClientResponse r = e.getResponse(); Assert.fail("Unexpected response " + r.getStatus() + " " + r.getEntity(String.class)); } Assert.assertNotNull(StringUtils.trimToNull(responseData.getClassPath())); Assert.assertEquals(1, responseData.getProperties().length); Assert.assertEquals("testProp1", responseData.getProperties()[0].getName()); Assert.assertEquals("testVal1", responseData.getProperties()[0].getValue()); //not sure of a better way to test this one yet... Assert.assertTrue(responseData.getResources().length > 0); }