List of usage examples for org.apache.commons.lang3 StringUtils endsWith
public static boolean endsWith(final CharSequence str, final CharSequence suffix)
Check if a CharSequence ends with a specified suffix.
null s are handled without exceptions.
From source file:com.ottogroup.bi.spqr.repository.CachedComponentClassLoader.java
/** * Initializes the class loader by pointing it to folder holding managed JAR files * @param componentFolder/*ww w. j a v a2 s .c o m*/ * @throws IOException * @throws RequiredInputMissingException */ public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException { /////////////////////////////////////////////////////////////////// // validate input if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'"); File folder = new File(componentFolder); if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder"); File[] jarFiles = folder.listFiles(); if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'"); // /////////////////////////////////////////////////////////////////// logger.info("Initializing component classloader [folder=" + componentFolder + "]"); // step through jar files, ensure it is a file and iterate through its contents for (File jarFile : jarFiles) { if (jarFile.isFile()) { JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); // if the current file references a class implementation, replace slashes by dots, strip // away the class suffix and add a reference to the classes-2-jar mapping if (StringUtils.endsWith(jarEntryName, ".class")) { jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); this.byteCode.put(jarEntryName, loadBytes(jarInputStream)); } else { // ...and add a mapping for resource to jar file as well this.resources.put(jarEntryName, loadBytes(jarInputStream)); } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } } } } logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation"); // load classes from jars marked component files and extract the deployment descriptors for (String cjf : this.byteCode.keySet()) { try { Class<?> c = loadClass(cjf); Annotation spqrComponentAnnotation = getSPQRComponentAnnotation(c); if (spqrComponentAnnotation != null) { Method spqrAnnotationTypeMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_TYPE_METHOD, (Class[]) null); Method spqrAnnotationNameMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_NAME_METHOD, (Class[]) null); Method spqrAnnotationVersionMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_VERSION_METHOD, (Class[]) null); Method spqrAnnotationDescriptionMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_DESCRIPTION_METHOD, (Class[]) null); @SuppressWarnings("unchecked") Enum<MicroPipelineComponentType> o = (Enum<MicroPipelineComponentType>) spqrAnnotationTypeMethod .invoke(spqrComponentAnnotation, (Object[]) null); final MicroPipelineComponentType componentType = Enum.valueOf(MicroPipelineComponentType.class, o.name()); final String componentName = (String) spqrAnnotationNameMethod.invoke(spqrComponentAnnotation, (Object[]) null); final String componentVersion = (String) spqrAnnotationVersionMethod .invoke(spqrComponentAnnotation, (Object[]) null); final String componentDescription = (String) spqrAnnotationDescriptionMethod .invoke(spqrComponentAnnotation, (Object[]) null); this.managedComponents.put(getManagedComponentKey(componentName, componentVersion), new ComponentDescriptor(c.getName(), componentType, componentName, componentVersion, componentDescription)); logger.info("pipeline component found [type=" + componentType + ", name=" + componentName + ", version=" + componentVersion + "]"); ; } } catch (Throwable e) { e.printStackTrace(); logger.error("Failed to load class '" + cjf + "'. Error: " + e.getMessage()); } } }
From source file:com.medlog.webservice.lifecycle.Security.java
private boolean hasAccess(String uri, String file, HttpServletRequest httprequest) { boolean hasAccess = isLoggedIn(httprequest) || isAPIRequest(httprequest) || StrUtl.regexTest(REG_EX_isNonSecurePages, StrUtl.toS(uri), true) || (!StringUtils.endsWith(uri, "html") && !StringUtils.endsWith(uri, "jsp")); if (DEBUG) {//www.j a va 2 s .c om log(String.format("User %s access to %s.", hasAccess ? "HAS" : "DOES HOT HAVE", StrUtl.toS(uri))); } return hasAccess; }
From source file:com.xpn.xwiki.plugin.activitystream.eventstreambridge.BridgeEventStream.java
/** * Convert an old {@link ActivityEvent} to the new {@link Event}. * // www .j a v a 2s . c o m * @param e the activity event to transform * @return the equivalent event */ private Event convertActivityToEvent(ActivityEvent e) { Event result = this.eventFactory.createRawEvent(); result.setApplication(e.getApplication()); result.setBody(e.getBody()); result.setDate(e.getDate()); result.setDocument(new DocumentReference(this.resolver.resolve(e.getPage(), EntityType.DOCUMENT))); result.setId(e.getEventId()); result.setDocumentTitle(e.getParam1()); if (StringUtils.isNotEmpty(e.getParam2())) { if (StringUtils.endsWith(e.getType(), "Attachment")) { result.setRelatedEntity( this.explicitResolver.resolve(e.getParam2(), EntityType.ATTACHMENT, result.getDocument())); } else if (StringUtils.endsWith(e.getType(), "Comment") || StringUtils.endsWith(e.getType(), "Annotation")) { result.setRelatedEntity( this.explicitResolver.resolve(e.getParam2(), EntityType.OBJECT, result.getDocument())); } } result.setImportance(Event.Importance.MEDIUM); if (e.getPriority() > 0) { int priority = e.getPriority() / 10 - 1; if (priority >= 0 && priority < Event.Importance.values().length) { result.setImportance(Event.Importance.values()[priority]); } } result.setGroupId(e.getRequestId()); result.setStream(e.getStream()); result.setTitle(e.getTitle()); result.setType(e.getType()); if (StringUtils.isNotBlank(e.getUrl())) { try { result.setUrl(new URL(e.getUrl())); } catch (MalformedURLException ex) { // Should not happen } } result.setUser(new DocumentReference(this.resolver.resolve(e.getUser(), EntityType.DOCUMENT))); result.setDocumentVersion(e.getVersion()); result.setParameters(e.getParameters()); return result; }
From source file:me.utils.excel.ImportExcelme.java
/** * ??/* w ww. j a v a 2 s . c o m*/ * @param cls */ public <E> List<E> getDataList(Class<E> cls, List<Zbx> zbxList) throws Exception { String title = (String) getMergedRegionValue(sheet, 0, 1);//? String tbDw = StringUtils.substringAfter((String) getMergedRegionValue(sheet, 1, 0), "");// Date tbDate = DateUtils .parseDate((StringUtils.substringAfter((String) getMergedRegionValue(sheet, 1, 4), ":")));//5? // Date tbDate = DateUtil.getJavaDate(Double.valueOf(StringUtils.substringAfter((String)getMergedRegionValue(sheet, 1, 4), ":"))) ;//5? Map<String, String> map = Maps.newHashMap(); for (Zbx zbx : zbxList) { map.put(zbx.getPropertyText(), zbx.getPropertyName()); } List<String> propertyNames = Lists.newArrayList(); for (int i = 0; i < this.getLastCellNum(); i++) {//?header ? Row row = this.getRow(this.getHeaderRowNum()); Object val = this.getCellValue(row, i); String propertyName = map.get(val); if (StringUtils.isEmpty(propertyName)) { throw new BusinessException("" + val + "?"); } propertyNames.add(propertyName); } //log.debug("Import column count:"+annotationList.size()); // Get excel data List<E> dataList = Lists.newArrayList(); for (int i = this.getDataRowNum(); i <= this.getLastDataRowNum(); i++) { E e = (E) cls.newInstance(); int column = 0; Row row = this.getRow(i); StringBuilder sb = new StringBuilder(); for (String propertyName : propertyNames) { Object val = this.getCellValue(row, column++);//string if (val != null) { // Get param type and type cast Class<?> valType = Reflections.getAccessibleField(e, propertyName).getType(); check(e, propertyName, val, i, column); //log.debug("Import value type: ["+i+","+column+"] " + valType); try { if (valType == String.class) { String s = String.valueOf(val.toString()); if (StringUtils.endsWith(s, ".0")) { val = StringUtils.substringBefore(s, ".0"); } else { val = String.valueOf(val.toString()); } } else if (valType == Integer.class) { val = Double.valueOf(val.toString()).intValue(); } else if (valType == Long.class) { val = Double.valueOf(val.toString()).longValue(); } else if (valType == Double.class) { val = Double.valueOf(val.toString()); } else if (valType == Float.class) { val = Float.valueOf(val.toString()); } else if (valType == Date.class) { // val = DateUtil.getJavaDate((Double)val); val = DateUtils.parseDate(val.toString()); } else {//? wjmany-to-one etc. } } catch (Exception ex) { log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString()); val = null; } // set entity value Reflections.invokeSetter(e, propertyName, val); } sb.append(val + ", "); } Reflections.invokeSetter(e, "title", title); Reflections.invokeSetter(e, "tbDw", tbDw); Reflections.invokeSetter(e, "tbDate", tbDate); dataList.add(e); log.debug("Read success: [" + i + "] " + sb.toString()); } return dataList; }
From source file:cn.calm.osgi.conter.FelixOsgiHost.java
protected List<String> getBundlesInDir(String dir) { List<String> bundleJars = new ArrayList<String>(); try {//from ww w . ja va 2 s .co m URL url = resource.find(dir); if (url != null) { if ("file".equals(url.getProtocol())) { File bundlesDir = new File(url.toURI()); File[] bundles = bundlesDir.listFiles(new FilenameFilter() { public boolean accept(File file, String name) { return StringUtils.endsWith(name, ".jar"); } }); if (bundles != null && bundles.length > 0) { // add all the bundles to the list for (File bundle : bundles) { String externalForm = bundle.toURI().toURL().toExternalForm(); if (LOG.isDebugEnabled()) { LOG.debug("Adding bundle [#0]", externalForm); } bundleJars.add(externalForm); } } else if (LOG.isDebugEnabled()) { LOG.debug("No bundles found under the [#0] directory", dir); } } else if (LOG.isWarnEnabled()) LOG.warn("Unable to read [#0] directory", dir); } else if (LOG.isWarnEnabled()) LOG.warn("The [#0] directory was not found", dir); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Unable load bundles from the [#0] directory", e, dir); } return bundleJars; }
From source file:annis.test.CsvResultSetProvider.java
public Object[] getArrayValue(int column, int sqlType) { String str = getStringValue(column); if (StringUtils.startsWith(str, "{") && StringUtils.endsWith(str, "}")) { String stripped = str.substring(1, str.length() - 1); String[] split = stripped.split(","); if (sqlType == Types.BIGINT) { Long[] result = new Long[split.length]; for (int i = 0; i < result.length; i++) { try { result[i] = Long.parseLong(split[i]); } catch (NumberFormatException ex) { log.error(null, ex); }//from w ww. ja v a 2s . c o m } return result; } else { // just return the string if requested so return split; } } return null; }
From source file:info.magnolia.security.setup.migration.MoveAclPermissionsBetweenWorkspaces.java
private String getExtraAclParameter(String acl) { if (StringUtils.endsWith(acl, everythingUnderThis)) { return everythingUnderThis; }//from w ww. ja v a 2s. c o m if (StringUtils.endsWith(acl, SelectedNode)) { return SelectedNode; } return StringUtils.EMPTY; }
From source file:com.ottogroup.bi.streaming.operator.json.statsd.StatsdExtractedMetricsReporter.java
/** * Extracts and reports a counter value/* w w w . j ava 2s. com*/ * @param metricCfg * The field configuration providing information on how to access and export content from JSON. Value is expected not to be null * @param json * The {@link JSONObject} to extract information from. Value is expected not to be null */ protected void reportCounter(final StatsdMetricConfig metricCfg, final JSONObject json) { String path = null; if (metricCfg.getDynamicPathPrefix() != null) { try { String dynPathPrefix = this.jsonUtils.getTextFieldValue(json, metricCfg.getDynamicPathPrefix().getPath(), false); if (StringUtils.isNotBlank(dynPathPrefix)) path = dynPathPrefix + (!StringUtils.endsWith(dynPathPrefix, ".") ? "." : "") + metricCfg.getPath(); else path = metricCfg.getPath(); } catch (Exception e) { // do nothing path = metricCfg.getPath(); } } else { path = metricCfg.getPath(); } if (!metricCfg.isReportDelta()) { this.statsdClient.incrementCounter(path); return; } if (metricCfg.getJsonRef().getContentType() == JsonContentType.INTEGER) { try { final Integer value = this.jsonUtils.getIntegerFieldValue(json, metricCfg.getJsonRef().getPath()); if (value != null) this.statsdClient.count(path, (metricCfg.getScaleFactor() != 1 ? value.longValue() * metricCfg.getScaleFactor() : value.longValue())); } catch (Exception e) { // do nothing } } else if (metricCfg.getJsonRef().getContentType() == JsonContentType.DOUBLE) { try { final Double value = this.jsonUtils.getDoubleFieldValue(json, metricCfg.getJsonRef().getPath()); if (value != null) this.statsdClient.count(path, (metricCfg.getScaleFactor() != 1 ? (long) (value.doubleValue() * metricCfg.getScaleFactor()) : value.longValue())); } catch (Exception e) { // do nothing } } }
From source file:com.ween.learn.util.excel.ImportExcel.java
/** * ??//from ww w .j av a 2 s . c o m * @param cls * @param groups */ public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException { List<Object[]> annotationList = Lists.newArrayList(); // Get annotation field Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { ExcelField ef = f.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == 2)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, f }); break; } } } } else { annotationList.add(new Object[] { ef, f }); } } } // Get annotation method Method[] ms = cls.getDeclaredMethods(); for (Method m : ms) { ExcelField ef = m.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == 2)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, m }); break; } } } } else { annotationList.add(new Object[] { ef, m }); } } } // Field sorting Collections.sort(annotationList, new Comparator<Object[]>() { public int compare(Object[] o1, Object[] o2) { return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort())); }; }); //log.debug("Import column count:"+annotationList.size()); // Get excel data List<E> dataList = Lists.newArrayList(); for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) { E e = (E) cls.newInstance(); int column = 0; Row row = this.getRow(i); StringBuilder sb = new StringBuilder(); for (Object[] os : annotationList) { Object val = this.getCellValue(row, column++); if (val != null) { ExcelField ef = (ExcelField) os[0]; // Get param type and type cast Class<?> valType = Class.class; if (os[1] instanceof Field) { valType = ((Field) os[1]).getType(); } else if (os[1] instanceof Method) { Method method = ((Method) os[1]); if ("get".equals(method.getName().substring(0, 3))) { valType = method.getReturnType(); } else if ("set".equals(method.getName().substring(0, 3))) { valType = ((Method) os[1]).getParameterTypes()[0]; } } //log.debug("Import value type: ["+i+","+column+"] " + valType); try { if (valType == String.class) { String s = String.valueOf(val.toString()); if (StringUtils.endsWith(s, ".0")) { val = StringUtils.substringBefore(s, ".0"); } else { val = String.valueOf(val.toString()); } } else if (valType == Integer.class) { val = Double.valueOf(val.toString()).intValue(); } else if (valType == Long.class) { val = Double.valueOf(val.toString()).longValue(); } else if (valType == Double.class) { val = Double.valueOf(val.toString()); } else if (valType == Float.class) { val = Float.valueOf(val.toString()); } else if (valType == Date.class) { val = DateUtil.getJavaDate((Double) val); } else { if (ef.fieldType() != Class.class) { val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString()); } else { val = Class .forName(this.getClass().getName().replaceAll( this.getClass().getSimpleName(), "fieldtype." + valType.getSimpleName() + "Type")) .getMethod("getValue", String.class).invoke(null, val.toString()); } } } catch (Exception ex) { log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString()); val = null; } // set entity value if (os[1] instanceof Field) { Reflections.invokeSetter(e, ((Field) os[1]).getName(), val); } else if (os[1] instanceof Method) { String mthodName = ((Method) os[1]).getName(); if ("get".equals(mthodName.substring(0, 3))) { mthodName = "set" + StringUtils.substringAfter(mthodName, "get"); } Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val }); } } sb.append(val + ", "); } dataList.add(e); log.debug("Read success: [" + i + "] " + sb.toString()); } return dataList; }
From source file:com.nike.vault.client.VaultClient.java
/** * Builds the full URL for preforming an operation against Vault. * * @param prefix Prefix between the environment URL and specified path * @param path Path for the requested operation * @return Full URL to execute a request against *///from w ww . j av a 2 s . com protected HttpUrl buildUrl(final String prefix, final String path) { String baseUrl = urlResolver.resolve(); if (!StringUtils.endsWith(baseUrl, "/")) { baseUrl += "/"; } return HttpUrl.parse(baseUrl + prefix + path); }