List of usage examples for org.apache.commons.lang3 StringUtils substringBeforeLast
public static String substringBeforeLast(final String str, final String separator)
Gets the substring before the last occurrence of a separator.
From source file:org.apache.nifi.web.api.RemoteProcessGroupResource.java
/** * Updates the specified remote process group. * * @param httpServletRequest request * @param id The id of the remote process group to update. * @param requestRemoteProcessGroupEntity A remoteProcessGroupEntity. * @return A remoteProcessGroupEntity.// w w w .java 2 s . c o m */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation(value = "Updates a remote process group", response = RemoteProcessGroupEntity.class, authorizations = { @Authorization(value = "Write - /remote-process-groups/{uuid}", type = "") }) @ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") }) public Response updateRemoteProcessGroup(@Context HttpServletRequest httpServletRequest, @ApiParam(value = "The remote process group id.", required = true) @PathParam("id") String id, @ApiParam(value = "The remote process group.", required = true) final RemoteProcessGroupEntity requestRemoteProcessGroupEntity) { if (requestRemoteProcessGroupEntity == null || requestRemoteProcessGroupEntity.getComponent() == null) { throw new IllegalArgumentException("Remote process group details must be specified."); } if (requestRemoteProcessGroupEntity.getRevision() == null) { throw new IllegalArgumentException("Revision must be specified."); } // ensure the ids are the same final RemoteProcessGroupDTO requestRemoteProcessGroup = requestRemoteProcessGroupEntity.getComponent(); if (!id.equals(requestRemoteProcessGroup.getId())) { throw new IllegalArgumentException(String.format( "The remote process group id (%s) in the request body does not equal the " + "remote process group id of the requested resource (%s).", requestRemoteProcessGroup.getId(), id)); } final PositionDTO proposedPosition = requestRemoteProcessGroup.getPosition(); if (proposedPosition != null) { if (proposedPosition.getX() == null || proposedPosition.getY() == null) { throw new IllegalArgumentException( "The x and y coordinate of the proposed position must be specified."); } } if (isReplicateRequest()) { return replicate(HttpMethod.PUT, requestRemoteProcessGroupEntity); } // handle expects request (usually from the cluster manager) final Revision requestRevision = getRevision(requestRemoteProcessGroupEntity, id); return withWriteLock(serviceFacade, requestRemoteProcessGroupEntity, requestRevision, lookup -> { Authorizable authorizable = lookup.getRemoteProcessGroup(id); authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, () -> serviceFacade.verifyUpdateRemoteProcessGroup(requestRemoteProcessGroup), (revision, remoteProcessGroupEntity) -> { final RemoteProcessGroupDTO remoteProcessGroup = remoteProcessGroupEntity.getComponent(); // if the target uri is set we have to verify it here - we don't support updating the target uri on // an existing remote process group, however if the remote process group is being created with an id // as is the case in clustered mode we need to verify the remote process group. treat this request as // though its a new remote process group. if (remoteProcessGroup.getTargetUri() != null) { // parse the uri final URI uri; try { uri = URI.create(remoteProcessGroup.getTargetUri()); } catch (final IllegalArgumentException e) { throw new IllegalArgumentException( "The specified remote process group URL is malformed: " + remoteProcessGroup.getTargetUri()); } // validate each part of the uri if (uri.getScheme() == null || uri.getHost() == null) { throw new IllegalArgumentException( "The specified remote process group URL is malformed: " + remoteProcessGroup.getTargetUri()); } if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) { throw new IllegalArgumentException( "The specified remote process group URL is invalid because it is not http or https: " + remoteProcessGroup.getTargetUri()); } // normalize the uri to the other controller String controllerUri = uri.toString(); if (controllerUri.endsWith("/")) { controllerUri = StringUtils.substringBeforeLast(controllerUri, "/"); } // update with the normalized uri remoteProcessGroup.setTargetUri(controllerUri); } // update the specified remote process group final RemoteProcessGroupEntity entity = serviceFacade.updateRemoteProcessGroup(revision, remoteProcessGroup); populateRemainingRemoteProcessGroupEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); }); }
From source file:org.apache.nifi.web.server.JettyServer.java
/** * Loads the WARs in the specified NAR working directories. A WAR file must * have a ".war" extension./* w ww. ja v a 2 s . com*/ * * @param narWorkingDirectories dirs */ private void loadWars(final Set<File> narWorkingDirectories) { // load WARs Map<File, File> warToNarWorkingDirectoryLookup = findWars(narWorkingDirectories); // locate each war being deployed File webUiWar = null; File webApiWar = null; File webErrorWar = null; File webDocsWar = null; File webContentViewerWar = null; List<File> otherWars = new ArrayList<>(); for (File war : warToNarWorkingDirectoryLookup.keySet()) { if (war.getName().toLowerCase().startsWith("nifi-web-api")) { webApiWar = war; } else if (war.getName().toLowerCase().startsWith("nifi-web-error")) { webErrorWar = war; } else if (war.getName().toLowerCase().startsWith("nifi-web-docs")) { webDocsWar = war; } else if (war.getName().toLowerCase().startsWith("nifi-web-content-viewer")) { webContentViewerWar = war; } else if (war.getName().toLowerCase().startsWith("nifi-web")) { webUiWar = war; } else { otherWars.add(war); } } // ensure the required wars were found if (webUiWar == null) { throw new RuntimeException("Unable to load nifi-web WAR"); } else if (webApiWar == null) { throw new RuntimeException("Unable to load nifi-web-api WAR"); } else if (webDocsWar == null) { throw new RuntimeException("Unable to load nifi-web-docs WAR"); } else if (webErrorWar == null) { throw new RuntimeException("Unable to load nifi-web-error WAR"); } else if (webContentViewerWar == null) { throw new RuntimeException("Unable to load nifi-web-content-viewer WAR"); } // handlers for each war and init params for the web api final HandlerCollection handlers = new HandlerCollection(); final Map<String, String> mimeMappings = new HashMap<>(); final ClassLoader frameworkClassLoader = getClass().getClassLoader(); final ClassLoader jettyClassLoader = frameworkClassLoader.getParent(); // deploy the other wars if (CollectionUtils.isNotEmpty(otherWars)) { // hold onto to the web contexts for all ui extensions componentUiExtensionWebContexts = new ArrayList<>(); contentViewerWebContexts = new ArrayList<>(); // ui extension organized by component type final Map<String, List<UiExtension>> componentUiExtensionsByType = new HashMap<>(); for (File war : otherWars) { // identify all known extension types in the war final Map<UiExtensionType, List<String>> uiExtensionInWar = new HashMap<>(); identifyUiExtensionsForComponents(uiExtensionInWar, war); // only include wars that are for custom processor ui's if (!uiExtensionInWar.isEmpty()) { // get the context path String warName = StringUtils.substringBeforeLast(war.getName(), "."); String warContextPath = String.format("/%s", warName); // attempt to locate the nar class loader for this war ClassLoader narClassLoaderForWar = NarClassLoaders.getInstance() .getExtensionClassLoader(warToNarWorkingDirectoryLookup.get(war)); // this should never be null if (narClassLoaderForWar == null) { narClassLoaderForWar = jettyClassLoader; } // create the extension web app context WebAppContext extensionUiContext = loadWar(war, warContextPath, narClassLoaderForWar); // create the ui extensions for (final Map.Entry<UiExtensionType, List<String>> entry : uiExtensionInWar.entrySet()) { final UiExtensionType extensionType = entry.getKey(); final List<String> types = entry.getValue(); if (UiExtensionType.ContentViewer.equals(extensionType)) { // consider each content type identified for (final String contentType : types) { // map the content type to the context path mimeMappings.put(contentType, warContextPath); } // this ui extension provides a content viewer contentViewerWebContexts.add(extensionUiContext); } else { // consider each component type identified for (final String componentType : types) { logger.info(String.format("Loading UI extension [%s, %s] for %s", extensionType, warContextPath, types)); // record the extension definition final UiExtension uiExtension = new UiExtension(extensionType, warContextPath); // create if this is the first extension for this component type List<UiExtension> componentUiExtensionsForType = componentUiExtensionsByType .get(componentType); if (componentUiExtensionsForType == null) { componentUiExtensionsForType = new ArrayList<>(); componentUiExtensionsByType.put(componentType, componentUiExtensionsForType); } // record this extension componentUiExtensionsForType.add(uiExtension); } // this ui extension provides a component custom ui componentUiExtensionWebContexts.add(extensionUiContext); } } // include custom ui web context in the handlers handlers.addHandler(extensionUiContext); } } // record all ui extensions to give to the web api componentUiExtensions = new UiExtensionMapping(componentUiExtensionsByType); } else { componentUiExtensions = new UiExtensionMapping(Collections.EMPTY_MAP); } // load the web ui app handlers.addHandler(loadWar(webUiWar, "/nifi", frameworkClassLoader)); // load the web api app webApiContext = loadWar(webApiWar, "/nifi-api", frameworkClassLoader); handlers.addHandler(webApiContext); // load the content viewer app webContentViewerContext = loadWar(webContentViewerWar, "/nifi-content-viewer", frameworkClassLoader); webContentViewerContext.getInitParams().putAll(mimeMappings); handlers.addHandler(webContentViewerContext); // create a web app for the docs final String docsContextPath = "/nifi-docs"; // load the documentation war webDocsContext = loadWar(webDocsWar, docsContextPath, frameworkClassLoader); // overlay the actual documentation final ContextHandlerCollection documentationHandlers = new ContextHandlerCollection(); documentationHandlers.addHandler(createDocsWebApp(docsContextPath)); documentationHandlers.addHandler(webDocsContext); handlers.addHandler(documentationHandlers); // load the web error app handlers.addHandler(loadWar(webErrorWar, "/", frameworkClassLoader)); // deploy the web apps server.setHandler(gzip(handlers)); }
From source file:org.apache.nutch.mapreduce.NutchCounter.java
@SuppressWarnings("rawtypes") public NutchCounter(TaskInputOutputContext context) { this.context = context; this.conf = context.getConfiguration(); this.id = counterSequence.incrementAndGet(); this.name = "NutchCounter" + "-" + id; String jobName = context.getJobName(); jobName = StringUtils.substringBeforeLast(jobName, "-"); jobName = jobName.replaceAll("(\\[.+\\])", ""); this.LOG = LoggerFactory.getLogger(name + "-" + jobName); this.hostname = NetUtil.getHostname(); crawlFilters = CrawlFilters.create(conf); }
From source file:org.apache.nutch.mapreduce.NutchReporter.java
public NutchReporter(NutchCounter counter) { this.counter = counter; this.context = counter.getContext(); this.conf = context.getConfiguration(); this.reportIntervalMillis = 1000 * conf.getInt("nutch.counter.report.interval.sec", 10); name = "NutchReporter-" + counter.id(); String jobName = context.getJobName(); jobName = StringUtils.substringBeforeLast(jobName, "-"); jobName = jobName.replaceAll("(\\[.+\\])", ""); this.LOG = LoggerFactory.getLogger(name + "-" + jobName); setName(name);/*w ww . j a va 2s . c o m*/ setDaemon(true); startReporter(); }
From source file:org.apache.nutch.util.StringUtil.java
public static void main(String[] args) { String counterName = "[beta_test_5]FetcherJob"; counterName = StringUtils.substringBeforeLast(counterName, "-"); System.out.println(counterName); counterName = counterName.replaceAll("(\\[.+\\])", ""); counterName = "counter." + counterName; System.out.println(counterName); }
From source file:org.apache.olingo.client.core.communication.request.retrieve.v4.XMLMetadataRequestImpl.java
@Override public ODataRetrieveResponse<org.apache.olingo.client.api.edm.xml.XMLMetadata> execute() { final SingleXMLMetadatRequestImpl rootReq = new SingleXMLMetadatRequestImpl((ODataClient) odataClient, uri); final ODataRetrieveResponse<XMLMetadata> rootRes = rootReq.execute(); final XMLMetadataResponseImpl response = new XMLMetadataResponseImpl(odataClient, httpClient, rootReq.getHttpResponse(), rootRes.getBody()); // process external references for (Reference reference : rootRes.getBody().getReferences()) { final SingleXMLMetadatRequestImpl includeReq = new SingleXMLMetadatRequestImpl( (ODataClient) odataClient, odataClient.newURIBuilder(reference.getUri().toASCIIString()).build()); final XMLMetadata includeMetadata = includeReq.execute().getBody(); // edmx:Include for (Include include : reference.getIncludes()) { final Schema includedSchema = includeMetadata.getSchema(include.getNamespace()); if (includedSchema != null) { response.getBody().getSchemas() .add((org.apache.olingo.client.api.edm.xml.v4.Schema) includedSchema); if (StringUtils.isNotBlank(include.getAlias())) { ((AbstractSchema) includedSchema).setAlias(include.getAlias()); }//from www. jav a 2s .c om } } // edmx:IncludeAnnotations for (IncludeAnnotations include : reference.getIncludeAnnotations()) { for (Schema schema : includeMetadata.getSchemas()) { // create empty schema that will be fed with edm:Annotations that match the criteria in IncludeAnnotations final SchemaImpl forInclusion = new SchemaImpl(); forInclusion.setNamespace(schema.getNamespace()); forInclusion.setAlias(schema.getAlias()); // process all edm:Annotations in each schema of the included document for (Annotations annotationGroup : ((SchemaImpl) schema).getAnnotationGroups()) { // take into account only when (TargetNamespace was either not provided or matches) and // (Qualifier was either not provided or matches) if ((StringUtils.isBlank(include.getTargetNamespace()) || include.getTargetNamespace() .equals(StringUtils.substringBeforeLast(annotationGroup.getTarget(), "."))) && (StringUtils.isBlank(include.getQualifier()) || include.getQualifier().equals(annotationGroup.getQualifier()))) { final AnnotationsImpl toBeIncluded = new AnnotationsImpl(); toBeIncluded.setTarget(annotationGroup.getTarget()); toBeIncluded.setQualifier(annotationGroup.getQualifier()); // only import annotations with terms matching the given TermNamespace for (Annotation annotation : annotationGroup.getAnnotations()) { if (include.getTermNamespace() .equals(StringUtils.substringBeforeLast(annotation.getTerm(), "."))) { toBeIncluded.getAnnotations().add(annotation); } } forInclusion.getAnnotationGroups().add(toBeIncluded); } } if (!forInclusion.getAnnotationGroups().isEmpty()) { response.getBody().getSchemas().add(forInclusion); } } } } return response; }
From source file:org.apache.olingo.client.core.communication.request.retrieve.XMLMetadataRequestImpl.java
@Override public ODataRetrieveResponse<XMLMetadata> execute() { SingleXMLMetadatRequestImpl rootReq = new SingleXMLMetadatRequestImpl(odataClient, uri, null); if (getPrefer() != null) { rootReq.setPrefer(getPrefer());//from ww w . j a v a2 s . c o m } if (getIfMatch() != null) { rootReq.setIfMatch(getIfMatch()); } if (getIfNoneMatch() != null) { rootReq.setIfNoneMatch(getIfNoneMatch()); } final ODataRetrieveResponse<XMLMetadata> rootRes = rootReq.execute(); if (rootRes.getStatusCode() != HttpStatusCode.OK.getStatusCode()) { return rootRes; } final XMLMetadataResponseImpl response = new XMLMetadataResponseImpl(odataClient, httpClient, rootReq.getHttpResponse(), rootRes.getBody()); // process external references for (Reference reference : rootRes.getBody().getReferences()) { final SingleXMLMetadatRequestImpl includeReq = new SingleXMLMetadatRequestImpl(odataClient, odataClient.newURIBuilder(uri.resolve(reference.getUri()).toASCIIString()).build(), uri); final XMLMetadata includeMetadata = includeReq.execute().getBody(); // edmx:Include for (Include include : reference.getIncludes()) { final CsdlSchema includedSchema = includeMetadata.getSchema(include.getNamespace()); if (includedSchema != null) { response.getBody().getSchemas().add(includedSchema); if (StringUtils.isNotBlank(include.getAlias())) { includedSchema.setAlias(include.getAlias()); } } } // edmx:IncludeAnnotations for (IncludeAnnotations include : reference.getIncludeAnnotations()) { for (CsdlSchema schema : includeMetadata.getSchemas()) { // create empty schema that will be fed with edm:Annotations that match the criteria in IncludeAnnotations final CsdlSchema forInclusion = new CsdlSchema(); forInclusion.setNamespace(schema.getNamespace()); forInclusion.setAlias(schema.getAlias()); // process all edm:Annotations in each schema of the included document for (CsdlAnnotations annotationGroup : schema.getAnnotationGroups()) { // take into account only when (TargetNamespace was either not provided or matches) and // (Qualifier was either not provided or matches) if ((StringUtils.isBlank(include.getTargetNamespace()) || include.getTargetNamespace() .equals(StringUtils.substringBeforeLast(annotationGroup.getTarget(), "."))) && (StringUtils.isBlank(include.getQualifier()) || include.getQualifier().equals(annotationGroup.getQualifier()))) { final CsdlAnnotations toBeIncluded = new CsdlAnnotations(); toBeIncluded.setTarget(annotationGroup.getTarget()); toBeIncluded.setQualifier(annotationGroup.getQualifier()); // only import annotations with terms matching the given TermNamespace for (CsdlAnnotation annotation : annotationGroup.getAnnotations()) { if (include.getTermNamespace() .equals(StringUtils.substringBeforeLast(annotation.getTerm(), "."))) { toBeIncluded.getAnnotations().add(annotation); } } forInclusion.getAnnotationGroups().add(toBeIncluded); } } if (!forInclusion.getAnnotationGroups().isEmpty()) { response.getBody().getSchemas().add(forInclusion); } } } } return response; }
From source file:org.apache.olingo.client.core.serialization.ContextURLParser.java
public static ContextURL parse(final URI contextURL) { if (contextURL == null) { return null; }// w w w . j av a 2s. c o m final ContextURL.Builder contextUrl = ContextURL.with(); String contextURLasString = contextURL.toASCIIString(); boolean isEntity = false; if (contextURLasString.endsWith("/$entity") || contextURLasString.endsWith("/@Element")) { isEntity = true; contextUrl.suffix(Suffix.ENTITY); contextURLasString = contextURLasString.replace("/$entity", StringUtils.EMPTY).replace("/@Element", StringUtils.EMPTY); } else if (contextURLasString.endsWith("/$ref")) { contextUrl.suffix(Suffix.REFERENCE); contextURLasString = contextURLasString.replace("/$ref", StringUtils.EMPTY); } else if (contextURLasString.endsWith("/$delta")) { contextUrl.suffix(Suffix.DELTA); contextURLasString = contextURLasString.replace("/$delta", StringUtils.EMPTY); } else if (contextURLasString.endsWith("/$deletedEntity")) { contextUrl.suffix(Suffix.DELTA_DELETED_ENTITY); contextURLasString = contextURLasString.replace("/$deletedEntity", StringUtils.EMPTY); } else if (contextURLasString.endsWith("/$link")) { contextUrl.suffix(Suffix.DELTA_LINK); contextURLasString = contextURLasString.replace("/$link", StringUtils.EMPTY); } else if (contextURLasString.endsWith("/$deletedLink")) { contextUrl.suffix(Suffix.DELTA_DELETED_LINK); contextURLasString = contextURLasString.replace("/$deletedLink", StringUtils.EMPTY); } contextUrl.serviceRoot(URI.create(StringUtils.substringBefore(contextURLasString, Constants.METADATA))); final String rest = StringUtils.substringAfter(contextURLasString, Constants.METADATA + "#"); String firstToken; String entitySetOrSingletonOrType; if (rest.startsWith("Collection(")) { firstToken = rest.substring(0, rest.indexOf(')') + 1); entitySetOrSingletonOrType = firstToken; } else { final int openParIdx = rest.indexOf('('); if (openParIdx == -1) { firstToken = StringUtils.substringBeforeLast(rest, "/"); entitySetOrSingletonOrType = firstToken; } else { firstToken = isEntity ? rest : StringUtils.substringBeforeLast(rest, ")") + ")"; final List<String> parts = new ArrayList<String>(); for (String split : firstToken.split("\\)/")) { parts.add(split.replaceAll("\\(.*", "")); } entitySetOrSingletonOrType = StringUtils.join(parts, '/'); final int commaIdx = firstToken.indexOf(','); if (commaIdx != -1) { contextUrl.selectList(firstToken.substring(openParIdx + 1, firstToken.length() - 1)); } } } contextUrl.entitySetOrSingletonOrType(entitySetOrSingletonOrType); final int slashIdx = entitySetOrSingletonOrType.lastIndexOf('/'); if (slashIdx != -1 && entitySetOrSingletonOrType.substring(slashIdx + 1).indexOf('.') != -1) { contextUrl.entitySetOrSingletonOrType(entitySetOrSingletonOrType.substring(0, slashIdx)); contextUrl.derivedEntity(entitySetOrSingletonOrType.substring(slashIdx + 1)); } if (!firstToken.equals(rest)) { final String[] pathElems = StringUtils.substringAfter(rest, "/").split("/"); if (pathElems.length > 0 && pathElems[0].length() > 0) { if (pathElems[0].indexOf('.') == -1) { contextUrl.navOrPropertyPath(pathElems[0]); } else { contextUrl.derivedEntity(pathElems[0]); } if (pathElems.length > 1) { contextUrl.navOrPropertyPath(pathElems[1]); } } } return contextUrl.build(); }
From source file:org.apache.olingo.commons.core.edm.primitivetype.AbstractGeospatialType.java
protected MultiLineString stringToMultiLineString(final String value, final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale, final Boolean isUnicode) throws EdmPrimitiveTypeException { final Matcher matcher = getMatcher(PATTERN, value); final List<LineString> lineStrings = new ArrayList<LineString>(); for (String coo : matcher.group(4).contains("),(") ? matcher.group(4).split("\\),\\(") : new String[] { matcher.group(4) }) { String lineString = coo;//from ww w. j av a 2 s . c o m if (lineString.charAt(0) == '(') { lineString = lineString.substring(1); } if (lineString.endsWith(")")) { lineString = StringUtils.substringBeforeLast(lineString, ")"); } lineStrings.add(newLineString(null, lineString, isNullable, maxLength, precision, scale, isUnicode)); } return new MultiLineString(this.dimension, SRID.valueOf(matcher.group(2)), lineStrings); }
From source file:org.apache.olingo.commons.core.edm.primitivetype.AbstractGeospatialType.java
protected MultiPolygon stringToMultiPolygon(final String value, final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale, final Boolean isUnicode) throws EdmPrimitiveTypeException { final Matcher matcher = getMatcher(PATTERN, value); final List<Polygon> polygons = new ArrayList<Polygon>(); for (String coo : matcher.group(4).contains(")),((") ? matcher.group(4).split("\\)\\),\\(\\(") : new String[] { matcher.group(4) }) { String polygon = coo;/* w w w . j ava 2 s .co m*/ if (polygon.startsWith("((")) { polygon = polygon.substring(1); } if (polygon.endsWith("))")) { polygon = StringUtils.substringBeforeLast(polygon, ")"); } if (polygon.charAt(0) != '(') { polygon = "(" + polygon; } if (!polygon.endsWith(")")) { polygon += ")"; } polygons.add(newPolygon(null, polygon, isNullable, maxLength, precision, scale, isUnicode)); } return new MultiPolygon(dimension, SRID.valueOf(matcher.group(2)), polygons); }