List of usage examples for org.apache.commons.lang StringUtils startsWith
public static boolean startsWith(String str, String prefix)
Check if a String starts with a specified prefix.
From source file:org.mule.module.mongo.MongoObjectStore.java
private boolean isPartition(final String collectionName) { return StringUtils.startsWith(collectionName, OBJECTSTORE_COLLECTION_PREFIX); }
From source file:org.mule.module.pubsubhubbub.HubTestCase.java
@Test public void testWrongMultivaluedRequest() throws Exception { final Map<String, List<String>> subscriptionRequest = new HashMap<String, List<String>>(); subscriptionRequest.put("hub.mode", Arrays.asList("subscribe", "unsubscribe")); final MuleMessage response = sendRequestToHub(subscriptionRequest); assertEquals("400", response.getInboundProperty("http.status")); assertTrue(StringUtils.startsWith(response.getPayloadAsString(), "Multivalued parameters are only supported for:")); }
From source file:org.mule.module.pubsubhubbub.PuSHHubModule.java
/** * Handle all hub requests.// w w w .j a va 2 s. c o m * <p/> * {@sample.xml ../../../doc/pubsubhubbub-connector.xml.sample * PuSH-hub:handleHubRequest} * * @param payload the message payload * @param httpMethod the HTTP method name * @param contentType the content-type of the request * @param responseHeaders the outbound/response headers * @return the response body * @throws Exception thrown in case anything goes haywire */ @Processor(name = "hub") public String handleHubRequest(@InboundHeaders(HttpConnector.HTTP_METHOD_PROPERTY) final String httpMethod, @InboundHeaders(HttpConstants.HEADER_CONTENT_TYPE) final String contentType, @OutboundHeaders final Map<String, Object> responseHeaders, @Payload final String payload) throws Exception { if (!StringUtils.equalsIgnoreCase(httpMethod, HttpConstants.METHOD_POST)) { return respond(responseHeaders, PuSHResponse.badRequest("HTTP method must be: POST")); } if (!StringUtils.startsWith(contentType, Constants.WWW_FORM_URLENCODED_CONTENT_TYPE)) { return respond(responseHeaders, PuSHResponse.badRequest("Content type must be: " + Constants.WWW_FORM_URLENCODED_CONTENT_TYPE)); } // TODO get encoding from current message: // @Expr(value = "#[message:encoding]") final String encoding, return respond(responseHeaders, handleRequest(payload, "UTF-8", Collections .singletonMap(Constants.HUB_DEFAULT_LEASE_SECONDS_PARAM, Long.toString(defaultLeaseSeconds)))); }
From source file:org.mule.modules.jive.api.xml.XmlMapper.java
/**Writes the xml of the internal data. * @param w The writer in which it'll write the xml * @param model The entity/*from w w w. ja v a2s.c o m*/ * @throws XMLStreamException When fails * */ @SuppressWarnings("unchecked") private void writeXML(final XMLStreamWriter w, final Map<String, Object> model) throws XMLStreamException { final Set<Entry<String, Object>> entries = model.entrySet(); for (final Entry<String, Object> entry : entries) { if (List.class.isInstance(entry.getValue())) { for (final String elem : (List<String>) entry.getValue()) { w.writeStartElement(entry.getKey()); w.writeCharacters(elem); w.writeEndElement(); } } else { String key = entry.getKey(); if (StringUtils.startsWith(key, "return")) { key = "return"; } w.writeStartElement(key); if (!HashMap.class.isInstance(entry.getValue())) { w.writeCharacters(entry.getValue().toString()); } else { writeXML(w, (HashMap<String, Object>) entry.getValue()); } w.writeEndElement(); } } }
From source file:org.mule.modules.jive.api.xml.XmlMapper.java
/**Maps an xml from a {@link Reader} to a {@link Map}. * @param reader The {@link Reader} with the xml data * @return The map with the entity data/*from w ww .j av a 2s. c o m*/ * */ @SuppressWarnings("unchecked") public final Map<String, Object> xml2map(final Reader reader) { final Map<String, Object> ret = new HashMap<String, Object>(); final Stack<Map<String, Object>> maps = new Stack<Map<String, Object>>(); Map<String, Object> current = ret; try { final XMLStreamReader r = xmlInputFactory.createXMLStreamReader(reader); StringBuilder lastText = new StringBuilder(); String currentElement = null; int returnCount = 0; while (r.hasNext()) { final int eventType = r.next(); if (eventType == CHARACTERS || eventType == CDATA || eventType == SPACE || eventType == ENTITY_REFERENCE) { lastText.append(r.getText()); } else if (eventType == END_DOCUMENT) { break; } else if (eventType == START_ELEMENT) { if (currentElement != null) { maps.push(current); final Map<String, Object> map = new HashMap<String, Object>(); if (StringUtils.startsWith(currentElement, "return")) { currentElement = currentElement + "--" + String.valueOf(returnCount); returnCount++; } current.put(currentElement, map); current = map; } currentElement = r.getLocalName(); } else if (eventType == END_ELEMENT) { if (currentElement == null) { current = maps.pop(); } else { current.put(currentElement, lastText.toString().trim()); currentElement = null; lastText = new StringBuilder(); } } else { throw new XMLStreamException("Unexpected event type " + eventType); } } final Object obj = ret.get(ret.keySet().iterator().next()); if (obj instanceof String) { Map<String, Object> responseTag = new HashMap<String, Object>(); responseTag.put("response", ret.keySet().iterator().next().toString()); return responseTag; } else { final Map<String, Object> returnXMLElement = (Map<String, Object>) ret .get(ret.keySet().iterator().next()); if (returnXMLElement.keySet().contains("return--1")) { return returnXMLElement; } return (Map<String, Object>) returnXMLElement.get("return--0"); } } catch (XMLStreamException e) { throw new UnhandledException(e); } }
From source file:org.nekorp.workflow.backend.memcache.ClienteDAOCache.java
public Object notifyQueryTodos(ProceedingJoinPoint pjp, FiltroCliente filtro, PaginationData<Long> pagination) throws Throwable { if (!StringUtils.isEmpty(filtro.getFiltroNombre())) { //esto es trampa, ya que si se permiten busquedas de diferentes longitudes no se van a poner //en el cache resultados de diferente longitud pagination.setMaxResults(0);// ww w.j a v a 2 s . co m String filtroOriginal = filtro.getFiltroNombre(); //se filtrara todo con una sola letra realmente. //TODO hacer configurable el numero de letras minimo para comenzar la busqueda String nuevoFiltro = StringUtils.substring(filtroOriginal, 0, 1); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); FiltroClienteCacheKey key = new FiltroClienteCacheKey(); key.setFiltro(nuevoFiltro); //log.info("sacando lista de clientes del cache"); @SuppressWarnings("unchecked") List<Cliente> value = (List<Cliente>) syncCache.get(key); if (value == null) { value = new LinkedList<Cliente>(); //log.info("la lista de clientes no estaba en el cache dejando hacer la busqueda al dao"); filtro.setFiltroNombre(nuevoFiltro); @SuppressWarnings("unchecked") List<Cliente> data = (List<Cliente>) pjp.proceed(); for (Cliente x : data) { value.add(x); } syncCache.put(key, value); filtro.setFiltroNombre(filtroOriginal); } List<Cliente> respuesta = value; //En caso de que el cliente quiera filtrar por mas de una letra //TODO hacer configurable el numero de letras minimo para comenzar la busqueda if (filtroOriginal.length() > 1) { respuesta = new LinkedList<Cliente>(); for (Cliente x : value) { if (StringUtils.startsWith(x.getNombreEstandar(), filtroOriginal)) { respuesta.add(x); } } } return respuesta; } else { return pjp.proceed(); } }
From source file:org.ngrinder.infra.AgentConfig.java
/** * Resolve NGrinder agent home path.//from w w w . j a va 2 s. c om * * @return resolved {@link AgentHome} */ protected AgentHome resolveHome() { String userHomeFromEnv = trimToEmpty(System.getenv("NGRINDER_AGENT_HOME")); //printLog(" System Environment: NGRINDER_AGENT_HOME={}", userHomeFromEnv); String userHomeFromProperty = trimToEmpty(System.getProperty("ngrinder.agent.home")); //printLog(" Java System Property: ngrinder.agent.home={}", userHomeFromEnv); if (StringUtils.isNotEmpty(userHomeFromEnv) && !StringUtils.equals(userHomeFromEnv, userHomeFromProperty)) { printLog("The path to ngrinder agent home is ambiguous:"); printLog(" '{}' is accepted.", userHomeFromProperty); } String userHome = StringUtils.defaultIfEmpty(userHomeFromProperty, userHomeFromEnv); if (StringUtils.isEmpty(userHome)) { userHome = System.getProperty("user.home") + File.separator + NGRINDER_DEFAULT_FOLDER; } else if (StringUtils.startsWith(userHome, "~" + File.separator)) { userHome = System.getProperty("user.home") + File.separator + userHome.substring(2); } else if (StringUtils.startsWith(userHome, "." + File.separator)) { userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2); } userHome = FilenameUtils.normalize(userHome); printLog("NGRINDER_AGENT_HOME : {}", userHome); File homeDirectory = new File(userHome); try { if (homeDirectory.mkdirs()) { noOp(); } if (!homeDirectory.canWrite()) { throw processException("home directory " + userHome + " is not writable."); } } catch (Exception e) { throw processException("Error while resolve the home directory.", e); } return new AgentHome(homeDirectory); }
From source file:org.nuxeo.eventlistener.AbortCreateDocumentSameTitleEventListener.java
/** * @param ctx//from w ww .ja va 2 s. co m * @return <code>true</code> if document can be created, <code>false</code> to cancel document's creation */ @Override protected boolean documentComplies(DocumentEventContext ctx) { DocumentModel doc = ctx.getSourceDocument(); String title = (String) doc.getPropertyValue("dc:title"); // checking if document has a title if (StringUtils.isEmpty(title)) { // Ignore document return true; } // checking if document is created under a specific folderish document if (!StringUtils.startsWith((String) ctx.getProperty(CoreEventConstants.DESTINATION_PATH), "/default-domain/workspaces/ws1")) { // Ignore document return true; } // rejecting documents with same title only of type 'File' if (!docTypesToCheck.contains(doc.getType())) { // Ignore document return true; } setMessage("document with same title already exists in " + (String) ctx.getProperty(CoreEventConstants.DESTINATION_PATH)); // retrieving parent folderish document DocumentRef parentRef = (DocumentRef) ctx.getProperty(CoreEventConstants.DESTINATION_REF); DocumentModel parentDoc = ctx.getCoreSession().getDocument(parentRef); // searching for documents with same title in the parent folderish document StringBuilder sb = new StringBuilder("SELECT " + NXQL.ECM_UUID + " FROM Document WHERE "); sb.append("dc:title").append(Operator.EQ.toString()).append(NXQL.escapeString(title)) .append(" " + Operator.AND.toString() + " ").append(NXQL.ECM_PARENTID) .append(Operator.EQ.toString()).append(NXQL.escapeString(parentDoc.getId())) .append(" " + Operator.AND.toString() + " ").append(NXQL.ECM_ISCHECKEDIN) .append(Operator.EQ.toString() + "0"); LOG.debug("NXQL query: " + sb.toString()); IterableQueryResult result = ctx.getCoreSession().queryAndFetch(sb.toString(), NXQL.NXQL); LOG.debug("result nbr: " + result.size()); return (result.size() == 0); }
From source file:org.okj.commons.net.FtpUtils.java
/** * FTP//from w ww . ja va 2 s . com * @param path */ public void changeWorkingDirectory(String path) { try { boolean flag = ftp.changeWorkingDirectory(path); if (flag) { // return; } else { // if (StringUtils.startsWith(path, File.separator)) { path = StringUtils.substring(path, 1); } String[] dirs = StringUtils.split(path, File.separator); if (dirs.length <= 0) { // return; } else { boolean success = ftp.changeWorkingDirectory(dirs[0]); if (LOGGER.isInfoEnabled()) { LOGGER.info("[FTPHelper] current.path=" + dirs[0] + ", success=" + success + ", working.dir=" + ftp.printWorkingDirectory()); } // String next = StringUtils.substring(path, StringUtils.indexOf(path, dirs[0]) + dirs[0].length()); changeWorkingDirectory(next); } } } catch (IOException ex) { LogUtils.error(LOGGER, "", ex); } }
From source file:org.sonar.updatecenter.deprecated.UpdateCenter.java
private History<Plugin> resolvePluginHistory(String id) throws Exception { String groupId = StringUtils.substringBefore(id, ":"); String artifactId = StringUtils.substringAfter(id, ":"); Artifact artifact = artifactFactory.createArtifact(groupId, artifactId, Artifact.LATEST_VERSION, Artifact.SCOPE_COMPILE, ARTIFACT_JAR_TYPE); List<ArtifactVersion> versions = filterSnapshots( metadataSource.retrieveAvailableVersions(artifact, localRepository, remoteRepositories)); History<Plugin> history = new History<Plugin>(); for (ArtifactVersion version : versions) { Plugin plugin = org.sonar.updatecenter.deprecated.Plugin .extractMetadata(resolve(artifact.getGroupId(), artifact.getArtifactId(), version.toString())); history.addArtifact(version, plugin); MavenProject project = mavenProjectBuilder .buildFromRepository(//w ww. j ava 2s . c o m artifactFactory.createArtifact(groupId, artifactId, version.toString(), Artifact.SCOPE_COMPILE, ARTIFACT_POM_TYPE), remoteRepositories, localRepository); if (plugin.getVersion() == null) { // Legacy plugin - set default values plugin.setKey(project.getArtifactId()); plugin.setName(project.getName()); plugin.setVersion(project.getVersion()); String sonarVersion = "1.10"; // TODO Is it minimal version for all extension points ? for (Dependency dependency : project.getDependencies()) { if ("sonar-plugin-api".equals(dependency.getArtifactId())) { // TODO dirty hack sonarVersion = dependency.getVersion(); } } plugin.setRequiredSonarVersion(sonarVersion); plugin.setHomepage(project.getUrl()); } plugin.setDownloadUrl(getPluginDownloadUrl(groupId, artifactId, plugin.getVersion())); // There is no equivalent for following properties in MANIFEST.MF if (project.getIssueManagement() != null) { plugin.setIssueTracker(project.getIssueManagement().getUrl()); } else { System.out.println("Unknown Issue Management for " + plugin.getKey() + ":" + plugin.getVersion()); } if (project.getScm() != null) { String scmUrl = project.getScm().getUrl(); if (StringUtils.startsWith(scmUrl, "scm:")) { scmUrl = StringUtils.substringAfter(StringUtils.substringAfter(scmUrl, ":"), ":"); } plugin.setSources(scmUrl); } else { System.out.println("Unknown SCM for " + plugin.getKey() + ":" + plugin.getVersion()); } if (project.getLicenses() != null && project.getLicenses().size() > 0) { plugin.setLicense(project.getLicenses().get(0).getName()); } else { System.out.println("Unknown License for " + plugin.getKey() + ":" + plugin.getVersion()); } if (project.getDevelopers().size() > 0) { plugin.setDevelopers(project.getDevelopers()); } else { System.out.println("Unknown Developers for " + plugin.getKey() + ":" + plugin.getVersion()); } } return history; }