List of usage examples for org.apache.commons.lang3 StringUtils startsWith
public static boolean startsWith(final CharSequence str, final CharSequence prefix)
Check if a CharSequence starts with a specified prefix.
null s are handled without exceptions.
From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java
/** * /* ww w . j ava 2 s . c o m*/ */ @Override public void run() { HttpEntity responseEntity = null; Map<String, String> params; if (urlValidator.isValid(smsGateway.getUrl())) { // Prepare the parameters to send params = new HashMap<>(); params.put("username", smsGateway.getUsername()); params.put("password", smsGateway.getPasswd()); params.put("source", smsSource.getSource()); params.put("message", message); switch (smsSource.getNetworkuuid()) { case Network.SAFARICOM_KE: params.put("network", "safaricom_ke"); break; case Network.AIRTEL_KE: params.put("network", "safaricom_ke"); // TODO: change to airtel_ke break; } // When setting the destination, numbers beginning with '07' are edited // to begin with '254' phoneMap = new HashMap<>(); StringBuffer phoneBuff = new StringBuffer(); String phoneNum; for (Phone phone : phoneList) { phoneNum = phone.getPhonenumber(); if (StringUtils.startsWith(phoneNum, "07")) { phoneNum = "254" + StringUtils.substring(phoneNum, 1); } phoneMap.put(phoneNum, phone); phoneBuff.append(phoneNum).append(";"); } params.put("destination", StringUtils.removeEnd(phoneBuff.toString(), ";")); // Push to the URL try { URL url = new URL(smsGateway.getUrl()); if (StringUtils.equalsIgnoreCase(url.getProtocol(), "http")) { responseEntity = doPost(smsGateway.getUrl(), params, retry); } // else if(StringUtils.equalsIgnoreCase(url.getProtocol(), "https")) { // doPostSecure(smsGateway.getUrl(), params, retry); // } } catch (MalformedURLException e) { logger.error("MalformedURLException for URL: '" + smsGateway.getUrl() + "'"); logger.error(ExceptionUtils.getStackTrace(e)); } } // end 'if(urlValidator.isValid(urlStr))' // Process the response from the SMS Gateway // Assuming all is ok, it would have the following pattern: // requestStatus=ACCEPTED&messageIds=254726176878:b265ce23;254728932844:367941a36d2e4ef195;254724300863:11fca3c5966d4d if (responseEntity != null) { OutgoingLog outgoingLog; try { String response = EntityUtils.toString(responseEntity); GatewayDAO.getInstance().logResponse(account, response, new Date()); String[] strTokens = StringUtils.split(response, '&'); String tmpStr = "", dateStr = ""; for (String str : strTokens) { if (StringUtils.startsWith(str, "messageIds")) { tmpStr = StringUtils.removeStart(str, "messageIds="); } else if (StringUtils.startsWith(str, "datetime")) { dateStr = StringUtils.removeStart(str, "datetime="); } } strTokens = StringUtils.split(tmpStr, ';'); String phoneStr, uuid; Phone phone; DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis(); for (String str : strTokens) { phoneStr = StringUtils.split(str, ':')[0]; uuid = StringUtils.split(str, ':')[1]; phone = phoneMap.get(phoneStr); outgoingLog = new OutgoingLog(); outgoingLog.setUuid(uuid); outgoingLog.setOrigin(smsSource.getSource()); outgoingLog.setMessage(message); outgoingLog.setDestination(phone.getPhonenumber()); outgoingLog.setNetworkUuid(phone.getNetworkuuid()); outgoingLog.setMessagestatusuuid(MsgStatus.SENT); outgoingLog.setSender(account.getUuid()); outgoingLog.setPhoneUuid(phone.getUuid()); // Set the date of the OutgoingLog to match the SMS Gateway time LocalDateTime datetime = timeFormatter.parseLocalDateTime(dateStr); outgoingLog.setLogTime(datetime.toDate()); outgoingLogDAO.put(outgoingLog); } } catch (ParseException e) { logger.error("ParseException when reading responseEntity"); logger.error(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { logger.error("IOException when reading responseEntity"); logger.error(ExceptionUtils.getStackTrace(e)); } } }
From source file:gobblin.instrumented.Instrumented.java
/** * Generates a new {@link gobblin.metrics.MetricContext} with the parent and tags taken from the reference context. * Allows replacing {@link gobblin.metrics.Tag} with new input tags. * This method will not copy any {@link gobblin.metrics.Metric} contained in the reference {@link gobblin.metrics.MetricContext}. * * @param context Reference {@link gobblin.metrics.MetricContext}. * @param newTags New {@link gobblin.metrics.Tag} to apply to context. Repeated keys will override old tags. * @param name Name of the new {@link gobblin.metrics.MetricContext}. * If absent or empty, will modify old name by adding a random integer at the end. * @return Generated {@link gobblin.metrics.MetricContext}. *//*from w ww . j av a 2 s . c om*/ public static MetricContext newContextFromReferenceContext(MetricContext context, List<Tag<?>> newTags, Optional<String> name) { String newName = name.orNull(); if (Strings.isNullOrEmpty(newName)) { UUID uuid = UUID.randomUUID(); String randomIdPrefix = "uuid:"; String oldName = context.getName(); List<String> splitName = Strings.isNullOrEmpty(oldName) ? Lists.<String>newArrayList() : Lists.newArrayList(Splitter.on(".").splitToList(oldName)); if (splitName.size() > 0 && StringUtils.startsWith(Iterables.getLast(splitName), randomIdPrefix)) { splitName.set(splitName.size() - 1, String.format("%s%s", randomIdPrefix, uuid.toString())); } else { splitName.add(String.format("%s%s", randomIdPrefix, uuid.toString())); } newName = Joiner.on(".").join(splitName); } MetricContext.Builder builder = context.getParent().isPresent() ? context.getParent().get().childBuilder(newName) : MetricContext.builder(newName); return builder.addTags(context.getTags()).addTags(newTags).build(); }
From source file:eu.openanalytics.rsb.component.JobsResource.java
/** * Handles a multi-part form job upload. * //from w w w. ja va2 s . co m * @param parts * @param httpHeaders * @param uriInfo * @return * @throws URISyntaxException * @throws IOException */ @POST @Consumes(Constants.MULTIPART_CONTENT_TYPE) // force content type to plain XML and JSON (browsers choke on subtypes) @Produces({ Constants.XML_CONTENT_TYPE, Constants.JSON_CONTENT_TYPE }) public Response handleMultipartFormJob(final List<Attachment> parts, @Context final HttpHeaders httpHeaders, @Context final UriInfo uriInfo) throws URISyntaxException, IOException { String applicationName = null; final Map<String, Serializable> jobMeta = new HashMap<String, Serializable>(); for (final Attachment part : parts) { final String partName = getPartName(part); if (StringUtils.equals(partName, Constants.APPLICATION_NAME_HTTP_HEADER)) { applicationName = part.getObject(String.class); } else if (StringUtils.startsWith(partName, Constants.RSB_META_HEADER_HTTP_PREFIX)) { final String metaName = StringUtils.substringAfter(partName, Constants.RSB_META_HEADER_HTTP_PREFIX); final String metaValue = part.getObject(String.class); if (StringUtils.isNotEmpty(metaValue)) { jobMeta.put(metaName, metaValue); } } } final String finalApplicationName = applicationName; return handleNewJob(finalApplicationName, httpHeaders, uriInfo, new JobBuilder() { @Override public AbstractJob build(final String applicationName, final UUID jobId, final GregorianCalendar submissionTime) throws IOException { final MultiFilesJob job = new MultiFilesJob(Source.REST, applicationName, getUserName(), jobId, submissionTime, jobMeta); for (final Attachment part : parts) { if (StringUtils.equals(getPartName(part), Constants.JOB_FILES_MULTIPART_NAME)) { final InputStream data = part.getDataHandler().getInputStream(); if (data.available() == 0) { // if the form is submitted with no file attached, we get // an empty part continue; } MultiFilesJob.addDataToJob(part.getContentType().toString(), getPartFileName(part), data, job); } } return job; } }); }
From source file:com.nridge.connector.common.con_com.crawl.CrawlIgnore.java
/** * Parses a file identified by the path/file name parameter * and loads it into an internally managed ignore URI list. * * @param aPathFileName Absolute file name (e.g. 'crawl_ignore.txt'). * * @throws IOException I/O related exception. *//*from www . j a v a 2 s . c o m*/ public void load(String aPathFileName) throws IOException { Pattern regexPattern; List<String> lineList; Logger appLogger = mAppMgr.getLogger(this, "load"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); try (FileReader fileReader = new FileReader(aPathFileName)) { lineList = IOUtils.readLines(fileReader); } for (String patternString : lineList) { if (!StringUtils.startsWith(patternString, "#")) { regexPattern = Pattern.compile(patternString); mPatternList.add(regexPattern); } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:ch.cyberduck.core.transfer.download.AbstractDownloadFilter.java
@Override public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException { final TransferStatus status = new TransferStatus(); if (parent.isExists()) { if (local.exists()) { if (file.getType().contains(Path.Type.file)) { if (local.isDirectory()) { throw new LocalAccessDeniedException(String.format("Cannot replace folder %s with file %s", local.getAbbreviatedPath(), file.getName())); }//from w w w . j a va2 s . c om } if (file.getType().contains(Path.Type.directory)) { if (local.isFile()) { throw new LocalAccessDeniedException(String.format("Cannot replace file %s with folder %s", local.getAbbreviatedPath(), file.getName())); } } status.setExists(true); } } final PathAttributes attributes; if (file.isSymbolicLink()) { // A server will resolve the symbolic link when the file is requested. final Path target = file.getSymlinkTarget(); // Read remote attributes of symlink target attributes = attribute.find(target); if (!symlinkResolver.resolve(file)) { if (file.isFile()) { // Content length status.setLength(attributes.getSize()); } } // No file size increase for symbolic link to be created locally } else { // Read remote attributes attributes = attribute.find(file); if (file.isFile()) { // Content length status.setLength(attributes.getSize()); if (StringUtils.startsWith(attributes.getDisplayname(), "file:")) { final String filename = StringUtils.removeStart(attributes.getDisplayname(), "file:"); if (!StringUtils.equals(file.getName(), filename)) { status.withDisplayname(LocalFactory.get(local.getParent(), filename)); int no = 0; while (status.getDisplayname().local.exists()) { String proposal = String.format("%s-%d", FilenameUtils.getBaseName(filename), ++no); if (StringUtils.isNotBlank(FilenameUtils.getExtension(filename))) { proposal += String.format(".%s", FilenameUtils.getExtension(filename)); } status.withDisplayname(LocalFactory.get(local.getParent(), proposal)); } } } } } status.setRemote(attributes); if (options.timestamp) { status.setTimestamp(attributes.getModificationDate()); } if (options.permissions) { Permission permission = Permission.EMPTY; if (preferences.getBoolean("queue.download.permissions.default")) { if (file.isFile()) { permission = new Permission(preferences.getInteger("queue.download.permissions.file.default")); } if (file.isDirectory()) { permission = new Permission( preferences.getInteger("queue.download.permissions.folder.default")); } } else { permission = attributes.getPermission(); } status.setPermission(permission); } status.setAcl(attributes.getAcl()); if (options.segments) { if (file.isFile()) { // Make segments if (status.getLength() >= preferences.getLong("queue.download.segments.threshold") && status.getLength() > preferences.getLong("queue.download.segments.size")) { final Download read = session.getFeature(Download.class); if (read.offset(file)) { if (log.isInfoEnabled()) { log.info(String.format("Split download %s into segments", local)); } long remaining = status.getLength(); long offset = 0; // Part size from default setting of size divided by maximum number of connections long partsize = Math.max(preferences.getLong("queue.download.segments.size"), status.getLength() / preferences.getInteger("queue.connections.limit")); // Sorted list final List<TransferStatus> segments = new ArrayList<TransferStatus>(); final Local segmentsFolder = LocalFactory.get(local.getParent(), String.format("%s.cyberducksegment", local.getName())); for (int segmentNumber = 1; remaining > 0; segmentNumber++) { final Local segmentFile = LocalFactory.get(segmentsFolder, String.format("%s-%d.cyberducksegment", local.getName(), segmentNumber)); boolean skip = false; // Last part can be less than 5 MB. Adjust part size. Long length = Math.min(partsize, remaining); final TransferStatus segmentStatus = new TransferStatus().segment(true).append(true) .skip(offset).length(length).rename(segmentFile); if (log.isDebugEnabled()) { log.debug(String.format("Adding status %s for segment %s", segmentStatus, segmentFile)); } segments.add(segmentStatus); remaining -= length; offset += length; } status.withSegments(segments); } } } } if (options.checksum) { status.setChecksum(attributes.getChecksum()); } return status; }
From source file:info.financialecology.finance.utilities.datastruct.VersatileChart.java
public void drawScatterPlot(VersatileDataTable acds, String... xyPairs) { ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>(); XYSeriesCollection dataSet = new XYSeriesCollection(); XYSeries xySeries = new XYSeries("no_name"); dataSet.addSeries(xySeries);//from ww w .jav a 2 s.co m for (int i = 0; i < xyPairs.length; i += 2) { List<String> rowKeys = acds.getRowKeys(); for (String rowKey : rowKeys) { if (!StringUtils.startsWith(rowKey, "#")) { double xValue = acds.getValue(rowKey, xyPairs[i]).doubleValue(); double yValue = acds.getValue(rowKey, xyPairs[i + 1]).doubleValue(); xySeries.add(xValue, yValue); } } JFreeChart chart = ChartFactory.createScatterPlot(params.title, params.xLabel, params.yLabel, dataSet, PlotOrientation.VERTICAL, params.legend, params.toolTips, false); charts.add(chart); } ChartFrame frame; for (JFreeChart chart : charts) { frame = new ChartFrame("UNKNOWN", chart); frame.pack(); frame.setVisible(true); } }
From source file:com.adobe.acs.commons.dam.impl.AssetsFolderPropertiesSupport.java
/** * Gateway method the Filter uses to determine if the request is a candidate for processing by Assets Folder Properties Support. * These checks should be fast and fail broadest and fastest first. * * @param request the request/*from w ww.j av a2 s . co m*/ * @return true if Assets Folder Properties Support should process this request. */ @SuppressWarnings("squid:S3923") protected boolean accepts(SlingHttpServletRequest request) { if (!StringUtils.equalsIgnoreCase(POST_METHOD, request.getMethod())) { // Only POST methods are processed return false; } else if (!DAM_FOLDER_SHARE_OPERATION.equals(request.getParameter(OPERATION))) { // Only requests with :operation=dam.share.folder are processed return false; } else if (!StringUtils.startsWith(request.getResource().getPath(), DAM_PATH_PREFIX)) { // Only requests under /content/dam are processed return false; } else if (!request.getResource().isResourceType(JcrResourceConstants.NT_SLING_FOLDER) && !request.getResource().isResourceType(JcrResourceConstants.NT_SLING_ORDERED_FOLDER)) { // Only requests to sling:Folders or sling:Ordered folders are processed return false; } // If the above checks do not fail, treat as a valid request return true; }
From source file:com.nridge.connector.common.con_com.crawl.CrawlStart.java
/** * Validates that there are files to crawl in the list and that each * file exists. This method is not appropriate for web site URLs. * * @throws NSException On empty list or access failures. *//* www . jav a 2s . c om*/ public void validate() throws NSException { File startFile; Logger appLogger = mAppMgr.getLogger(this, "validate"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mStartList.size() == 0) throw new NSException("The starting crawl list is empty."); for (String startName : mStartList) { if (StringUtils.startsWith(startName, "http")) { HttpGet httpGet = new HttpGet(startName); CloseableHttpResponse httpResponse = null; CloseableHttpClient httpClient = createHttpClient(); try { httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if ((statusCode >= HTTP_STATUS_OK_START) && (statusCode <= HTTP_STATUS_OK_END) || (statusCode >= HTTP_STATUS_REDIRECTION_START) && (statusCode <= HTTP_STATUS_REDIRECTION_END)) { HttpEntity httpEntity = httpResponse.getEntity(); EntityUtils.consume(httpEntity); } else { String msgStr = String.format("%s (status code %d): %s", startName, statusCode, httpResponse.getStatusLine()); throw new NSException(msgStr); } } catch (IOException e) { String msgStr = String.format("%s: %s", startName, e.getMessage()); throw new NSException(msgStr); } finally { if (httpResponse != null) IOUtils.closeQuietly(httpResponse); } } else { startFile = new File(startName); if ((!startFile.exists()) || (!startFile.canRead())) throw new NSException(String.format("%s: Cannot be accessed for crawl.", startName)); } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.glaf.dts.web.rest.MxQueryResource.java
@POST @Path("/saveQuery") @ResponseBody// w w w . ja v a 2 s. co m @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public byte[] saveQuery(@Context HttpServletRequest request) { String queryId = request.getParameter("queryId"); QueryDefinition query = null; if (StringUtils.isNotEmpty(queryId)) { query = queryDefinitionService.getQueryDefinition(queryId); } if (query == null) { query = new QueryDefinition(); } Map<String, Object> params = RequestUtils.getParameterMap(request); Tools.populate(query, params); logger.debug("sql:" + query.getSql()); logger.debug("targetTableName:" + query.getTargetTableName()); logger.debug("parentId:" + query.getParentId()); MxTransformManager manager = new MxTransformManager(); if (StringUtils.isNotEmpty(query.getSql())) { if (!DBUtils.isLegalQuerySql(query.getSql())) { return ResponseUtils.responseJsonResult(false, "SQL?????"); } if (!DBUtils.isAllowedSql(query.getSql())) { return ResponseUtils.responseJsonResult(false, "SQL?????"); } if (StringUtils.isNotEmpty(query.getTargetTableName())) { String tableName = query.getTargetTableName(); tableName = tableName.toLowerCase(); if (tableName.length() > 26) { return ResponseUtils.responseJsonResult(false, "?26?"); } if (StringUtils.startsWith(tableName, "mx_") || StringUtils.startsWith(tableName, "sys_") || StringUtils.startsWith(tableName, "jbpm_") || StringUtils.startsWith(tableName, "act_")) { return ResponseUtils.responseJsonResult(false, "??"); } } TableDefinition newTable = null; try { newTable = manager.toTableDefinition(query); } catch (Exception ex) { ex.printStackTrace(); return ResponseUtils.responseJsonResult(false, "SQL???"); } if (StringUtils.isNotEmpty(query.getTargetTableName())) { newTable.setTableName(query.getTargetTableName()); TableDefinition table = tableDefinitionService.getTableDefinition(query.getTargetTableName()); if (table == null) { table = newTable; } else { if (newTable != null && newTable.getColumns() != null) { for (ColumnDefinition column : newTable.getColumns()) { if (!table.getColumns().contains(column)) { table.addColumn(column); } } } } tableDefinitionService.save(table); } if (newTable != null && newTable.getColumns() != null) { } query.setType(Constants.DTS_TASK_TYPE); queryDefinitionService.save(query); } return ResponseUtils.responseJsonResult(true); }
From source file:com.nridge.connector.common.con_com.transform.TCPCCollapse.java
private DataBag collapse(DataBag aParentBag, DataBag aChildBag, String aChildDocType) { String fieldName;//from w w w . j a v a2 s . c o m DataField collapseField; Logger appLogger = mAppMgr.getLogger(this, "collapse"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); String idFieldName = mFieldNamePrefix + "id"; DataBag collapseBag = new DataBag(aParentBag); for (DataField childField : aChildBag.getFields()) { fieldName = childField.getName(); if ((!StringUtils.startsWith(fieldName, "nsd_")) && (!StringUtils.equals(fieldName, idFieldName))) { fieldName = String.format("rel_%s_%s", Field.titleToName(aChildDocType), childField.getName()); collapseField = collapseBag.getFieldByName(fieldName); if (collapseField == null) { collapseField = new DataField(childField); collapseField.setName(fieldName); collapseField.setMultiValueFlag(true); collapseBag.add(collapseField); } else { if (!collapseField.isMultiValue()) collapseField.setMultiValueFlag(true); collapseField.addValue(childField.getValue()); } } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return collapseBag; }