Example usage for org.apache.commons.lang.text StrSubstitutor replace

List of usage examples for org.apache.commons.lang.text StrSubstitutor replace

Introduction

In this page you can find the example usage for org.apache.commons.lang.text StrSubstitutor replace.

Prototype

public static String replace(Object source, Map valueMap) 

Source Link

Document

Replaces all the occurrences of variables in the given source object with their matching values from the map.

Usage

From source file:de.brands4friends.daleq.core.StringTemplateValue.java

@Override
public Object transform(final long value) {
    return StrSubstitutor.replace(this.template, ImmutableMap.of(VAR_NAME, value));
}

From source file:com.wso2telco.gsma.authenticators.util.USSDOutboundMessage.java

public static String prepare(MessageType messageType, HashMap<String, String> map, String operator) {

    MobileConnectConfig.OperatorSpecificMessage operatorSpecificMessage = null;
    String template = "";
    Map<String, String> data = new HashMap<String, String>();
    // add default map values here
    // data.put("key", "value");

    if (map != null && map.size() > 0) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            data.put(entry.getKey(), entry.getValue());
        }//from w  w  w  .j a v  a 2  s . c om
    }

    // Load operator specific message from hash map
    if (operator != null) {
        operatorSpecificMessage = operatorSpecificMessageMap.get(operator);
        data.put("operator", operator);
    }

    if (operatorSpecificMessage != null) {
        if (messageType == MessageType.LOGIN) {
            template = operatorSpecificMessage.getLoginMessage();
        }

        if (messageType == MessageType.REGISTRATION) {
            template = operatorSpecificMessage.getRegistrationMessage();
        }
    } else {
        if (messageType == MessageType.LOGIN) {
            template = ussdConfig.getUssdLoginMessage();
        }

        if (messageType == MessageType.REGISTRATION) {
            template = ussdConfig.getUssdRegistrationMessage();
        }
    }

    return StrSubstitutor.replace(template, data);
}

From source file:eu.eexcess.kimportal.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {
    // Configure/* w ww  .j  a  va2 s.com*/
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientDefault());

        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);

        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        int numResults = 10;
        if (userProfile.numResults != null && userProfile.numResults != 0)
            numResults = userProfile.numResults;
        valuesMap.put("numResults", numResults + "");

        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        client.destroy();
        return builder.get(Document.class);
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:at.bestsolution.efxclipse.tooling.rrobot.impl.RRobotImpl.java

@Override
public IStatus executeTask(IProgressMonitor monitor, RobotTask task, Map<String, Object> additionalData) {

    // We'll operate on a copy because we modify the model and replace variable
    if (!task.getVariables().isEmpty()) {
        task = EcoreUtil.copy(task);//w w  w .ja  v a2s  .c o m
    }

    System.err.println("ADDITIONAL: " + additionalData);

    for (Variable v : task.getVariables()) {
        if (!additionalData.containsKey(v.getKey())) {
            additionalData.put(v.getKey(), getVariableData(v));
        }
    }

    for (Entry<String, Object> e : additionalData.entrySet()) {
        if (e.getValue() instanceof String) {
            e.setValue(StrSubstitutor.replace((String) e.getValue(), additionalData));
        }
    }

    List<ProjectHandler<Project>> handlers;

    synchronized (this.handlers) {
        handlers = new ArrayList<ProjectHandler<Project>>(this.handlers);
    }

    TreeIterator<EObject> it = task.eAllContents();
    while (it.hasNext()) {
        EObject eo = it.next();
        for (EStructuralFeature f : eo.eClass().getEAllStructuralFeatures()) {
            Object val = eo.eGet(f);
            if (val instanceof String) {
                //               System.err.println("REPLACING: " + f + " val: " + val);
                eo.eSet(f, StrSubstitutor.replace(val, additionalData));
            }
        }
    }

    System.err.println("ADDITIONAL: " + additionalData);

    List<IStatus> states = new ArrayList<IStatus>();
    for (Project p : task.getProjects()) {
        for (ProjectHandler<Project> handler : handlers) {
            if (handler.isHandled(p.eClass())) {
                states.add(handler.createProject(monitor, p, additionalData));
            }
        }
    }

    return new MultiStatus("at.bestsolution.efxclipse.tooling.rrobot", 0, states.toArray(new IStatus[0]),
            "Task executed", null);
}

From source file:eu.eexcess.kimcollect.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure/*w  w w.  ja v a 2 s  . c om*/
    try {

        //        ClientConfig config = new DefaultClientConfig();
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientDefault());

        //        client.addFilter(new HTTPBasicAuthFilter(partnerConfiguration.userName, partnerConfiguration.password));

        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);

        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        int numResults = 10;
        if (userProfile.numResults != null && userProfile.numResults != 0)
            numResults = userProfile.numResults;
        valuesMap.put("numResults", numResults + "");

        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        client.destroy();
        return builder.get(Document.class);
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:eu.eexcess.wissenmedia.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure//from   w  w  w . ja  v  a2s .c o  m
    try {

        //        ClientConfig config = new DefaultClientConfig();
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientDefault());

        client.addFilter(new HTTPBasicAuthFilter(partnerConfiguration.userName, partnerConfiguration.password));

        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);

        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", URLParamEncoder.encode(query));
        int numResults = 10;
        if (userProfile.numResults != null && userProfile.numResults != 0)
            numResults = userProfile.numResults;
        valuesMap.put("numResults", numResults + "");

        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        Builder builder = service.accept(MediaType.APPLICATION_XML);
        client.destroy();
        return builder.get(Document.class);
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure//from   w w w .j  a  v a2  s .  co  m
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJAXBContext());
        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);
        query = query.replaceAll("\"", "");
        query = query.replaceAll("\\(", " ");
        query = query.replaceAll("\\)", " ");
        query = URLEncoder.encode(query, "UTF-8");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        if (userProfile.numResults != null)
            valuesMap.put("size", userProfile.numResults.toString());
        else
            valuesMap.put("size", "10");
        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        log.log(Level.INFO, "SearchRequest: " + searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        String response = builder.get(String.class);
        StringReader respStringReader = new StringReader(response);
        client.destroy();
        JAXBContext jaxbContext = JAXBContext.newInstance(ZBWDocument.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ZBWDocument zbwResponse = (ZBWDocument) jaxbUnmarshaller.unmarshal(respStringReader);
        for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
            try {
                if (hit.element.type.equals("event")) {
                    Document detail = fetchDocumentDetails(hit.element.id);
                    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, detail, "detail-response",
                            logger);
                    String latValue = getValueWithXPath("/doc/record/geocode/lat", detail);
                    String longValue = getValueWithXPath("/doc/record/geocode/lng", detail);
                    hit.element.lat = latValue;
                    hit.element.lng = longValue;
                }
            } catch (Exception e) {
                log.log(Level.WARNING,
                        "Could not get longitude and latitude for event element " + hit.element.id, e);
            }
            // put all creators in the creatorString
            if (hit.element.creator != null) {
                for (String creator : hit.element.creator) {
                    if (hit.element.creatorString == null)
                        hit.element.creatorString = "";
                    if (hit.element.creatorString.length() > 0)
                        hit.element.creatorString += ", ";
                    hit.element.creatorString += creator;
                }
            }
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(zbwResponse, document);

        return document;
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:at.bestsolution.fxide.jdt.maven.MavenParentModuleTypeService.java

@Override
public Status createModule(IProject project, IResource resource) {
    IProjectDescription description = project.getWorkspace().newProjectDescription(project.getName());
    description.setNatureIds(new String[] { JavaCore.NATURE_ID, "org.eclipse.m2e.core.maven2Nature" });

    ICommand[] commands = new ICommand[1];

    {/*from   ww w  .j  a  v  a 2 s.co  m*/
        ICommand cmd = description.newCommand();
        cmd.setBuilderName("org.eclipse.m2e.core.maven2Builder");
        commands[0] = cmd;
    }

    // If we get a parent path we create a nested project
    if (resource != null) {
        try {
            if (resource.getProject().getNature("org.eclipse.m2e.core.maven2Nature") != null) {
                description.setLocation(resource.getProject().getFullPath().append(project.getName()));
            }
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    description.setBuildSpec(commands);

    try {
        project.create(description, null);
        project.open(null);

        project.getFolder(new Path("target")).create(true, true, null);
        project.getFolder(new Path("target")).setDerived(true, null);

        project.getFolder(new Path("src")).create(true, true, null);
        project.getFolder(new Path("src").append("site")).create(true, true, null);

        {
            IFile file = project.getFile(new Path("pom.xml"));
            try (InputStream templateStream = getClass().getResourceAsStream("template-parent-pom.xml")) {
                String pomContent = IOUtils.readToString(templateStream, Charset.forName("UTF-8"));
                Map<String, String> map = new HashMap<>();
                map.put("groupId", project.getName());
                map.put("artifactId", project.getName());
                map.put("version", "1.0.0");

                try (ByteArrayInputStream in = new ByteArrayInputStream(
                        StrSubstitutor.replace(pomContent, map).getBytes());
                        ByteArrayOutputStream out = new ByteArrayOutputStream();) {
                    Model model = MavenPlugin.getMaven().readModel(in);
                    MavenPlugin.getMaven().writeModel(model, out);
                    try (ByteArrayInputStream in2 = new ByteArrayInputStream(out.toByteArray())) {
                        file.create(in2, true, null);
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        project.getWorkspace().save(true, null);
    } catch (CoreException ex) {
        return Status.status(State.ERROR, -1, "Failed to create project", ex);
    }

    return Status.ok();
}

From source file:eu.eexcess.partnerwizard.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {
    Map<String, String> parameters = new HashMap<>();

    QueryGeneratorApi queryGenerator = PartnerConfigurationCache.CONFIG
            .getQueryGenerator(partnerConfiguration.getQueryGeneratorClass());
    String query = queryGenerator.toQuery(userProfile);
    parameters.put("query", query);

    Integer numberOfResults = userProfile.getNumResults();
    if (numberOfResults != null && numberOfResults > 0) {
        parameters.put(NUMBER_OF_RESULTS_PARAMETER_NAME, numberOfResults.toString());
    } else {//from   w  w w  .  j  av  a  2s.c o  m
        parameters.put(NUMBER_OF_RESULTS_PARAMETER_NAME, NUMBER_OF_RESULTS_PARAMETER);
    }

    String userName = partnerConfiguration.getUserName();
    if (userName != null && !userName.isEmpty()) {
        parameters.put(USER_NAME_PARAMETER_NAME, userName);
    }

    String password = partnerConfiguration.getPassword();
    if (password != null && !password.isEmpty()) {
        parameters.put(PASSWORD_PARAMETER_NAME, password);
    }

    String apiKey = partnerConfiguration.getApiKey();
    if (apiKey != null && !apiKey.isEmpty()) {
        parameters.put(API_KEY_PARAMETER_NAME, apiKey);
    }

    String searchUrl = StrSubstitutor.replace(partnerConfiguration.getSearchEndpoint(), parameters);

    Client client = new Client(PartnerConfigurationCache.CONFIG.getClientDefault());
    WebResource.Builder builder = client.resource(searchUrl).accept(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_XML_TYPE);
    ClientResponse response;
    try {
        response = builder.get(ClientResponse.class);
    } catch (ClientHandlerException | UniformInterfaceException ex) {
        LOGGER.log(Level.SEVERE, "Search URL:{0}", searchUrl);
        throw new IOException("Cannot query partner API! URL: " + searchUrl, ex);
    }
    try {
        return parseResponse(response);
    } catch (EEXCESSDataTransformationException ex) {
        throw new IOException("The partner's response could not be parsed", ex);
    }
}

From source file:eu.eexcess.europeana.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure//from w  ww  . ja v a 2  s .c o  m
    ExecutorService threadPool = Executors.newFixedThreadPool(10);

    //        ClientConfig config = new DefaultClientConfig();
    //        config.getClasses().add(JacksonJsonProvider.class);
    //        
    final Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJacksonJson());
    queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();
    String query = getQueryGenerator().toQuery(userProfile);
    long start = System.currentTimeMillis();

    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("query", URLParamEncoder.encode(query));
    valuesMap.put("apiKey", partnerConfiguration.apiKey); // add API key
    // searchEndpoint: "http://www.europeana.eu/api/v2/search.json?wskey=${apiKey}&query=${query}"
    int numResultsRequest = 10;
    if (userProfile.numResults != null && userProfile.numResults != 0)
        numResultsRequest = userProfile.numResults;
    valuesMap.put("numResults", numResultsRequest + "");
    String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

    WebResource service = client.resource(searchRequest);
    ObjectMapper mapper = new ObjectMapper();
    Builder builder = service.accept(MediaType.APPLICATION_JSON);
    EuropeanaResponse response = builder.get(EuropeanaResponse.class);
    if (response.items.size() > numResultsRequest)
        response.items = response.items.subList(0, numResultsRequest);
    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, response.toString(), "service-response",
            PartnerdataTracer.FILETYPE.JSON, logger);
    client.destroy();
    if (makeDetailRequests) {
        HashMap<EuropeanaDoc, Future<Void>> futures = new HashMap<EuropeanaDoc, Future<Void>>();
        final HashMap<EuropeanaDoc, EuropeanaDocDetail> docDetails = new HashMap<EuropeanaDoc, EuropeanaDocDetail>();
        final PartnerConfiguration partnerConfigLocal = partnerConfiguration;
        final String eexcessRequestId = logger.getActLogEntry().getRequestId();
        for (int i = 0; i < response.items.size(); i++) {
            final EuropeanaDoc item = response.items.get(i);

            Future<Void> future = threadPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    EuropeanaDocDetail details = null;
                    try {
                        details = fetchDocumentDetails(item.id, partnerConfigLocal, eexcessRequestId);
                    } catch (EEXCESSDataTransformationException e) {
                        log.log(Level.INFO, "Error getting item with id" + item.id, e);
                        return null;
                    }
                    docDetails.put(item, details);
                    return null;
                }
            });
            futures.put(item, future);
        }

        for (EuropeanaDoc doc : futures.keySet()) {
            try {
                futures.get(doc).get(start + 15 * 500 - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                log.log(Level.WARNING, "Detail thread for " + doc.id + " did not responses in time", e);
            }

            //item.edmConcept.addAll(details.concepts);
            //         item.edmConcept = details.concepts; TODO: copy into doc
            //         item.edmCountry = details.edmCountry;
            //         item.edmPlace = details.places;
        }
    }

    long end = System.currentTimeMillis();

    long startXML = System.currentTimeMillis();

    Document newResponse = null;
    try {
        newResponse = this.transformJSON2XML(mapper.writeValueAsString(response));
    } catch (EEXCESSDataTransformationException e) {
        // TODO logger

        log.log(Level.INFO, "Error Transforming Json to xml", e);

    }
    long endXML = System.currentTimeMillis();
    System.out.println("millis " + (endXML - startXML) + "   " + (end - start));

    threadPool.shutdownNow();

    return newResponse;

}