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:com.ariht.maven.plugins.config.ConfigProcessorMojo.java

/**
 * Read properties from filter file and substitute template place-holders.
 * Write results to output path with same relative path as input filters.
 *
 * Typical output is to ...target/filter-sub-dir/template-dir/template.name
 *//*from www.j a v a 2 s.  c o m*/
private void generateConfig(final FileInfo template, final FileInfo filter, final String outputBasePath)
        throws IOException, ConfigurationException {
    final String outputDirectory = createOutputDirectory(template, filter, outputBasePath);
    final String templateFilename = template.getFile().getName();
    final String outputFilename = FilenameUtils.separatorsToSystem(outputDirectory + templateFilename);
    if (logOutput) {
        getLog().info("Generating : " + String.valueOf(outputFilename));
    } else if (getLog().isDebugEnabled()) {
        getLog().debug("Generating : " + String.valueOf(outputFilename));
    }
    getLog().debug("Applying filter : " + filter.toString() + " to template : " + template.toString());
    final String rawTemplate = FileUtils.readFileToString(template.getFile());
    final Properties properties = readFilterIntoProperties(filter);
    final String processedTemplate = StrSubstitutor.replace(rawTemplate, properties);

    if (StringUtils.isNotBlank(encoding)) {
        FileUtils.writeStringToFile(new File(outputFilename), processedTemplate, encoding);
    } else {
        FileUtils.writeStringToFile(new File(outputFilename), processedTemplate);
    }
}

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

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

    //          final String url = "https://api.deutsche-digitale-bibliothek.de/items/OAXO2AGT7YH35YYHN3YKBXJMEI77W3FF/view";
    final String key = PartnerConfigurationEnum.CONFIG.getPartnerConfiguration().apiKey;

    // get XML data via HTTP request header authentication
    /*//from w  w w  . ja  va 2  s.c o m
    // get JSON data via HTTP request header authentication
    String httpJsonResult = httpGet(url, new HashMap<String, String>() {
       {
           put("Authorization", "OAuth oauth_consumer_key=\"" + key + "\"");
           put("Accept", "application/json");
       }
    });
    logger.info(httpJsonResult); // print results
            
    // get JSON data via query parameter authentication
    // remember: use URL encoded Strings online -> URLEncoder.encode(s, enc)
    String queryJsonURL = url + "?oauth_consumer_key=" + URLEncoder.encode(key, "UTF-8");
    String queryJsonResult = httpGet(queryJsonURL, null);
    logger.info(queryJsonResult); // print results
    */

    //
    //
    // EUROPEANA Impl
    //
    //

    // Configure
    ExecutorService threadPool = Executors.newFixedThreadPool(10);

    //        ClientConfig config = new DefaultClientConfig();
    //        config.getClasses().add(JacksonJsonProvider.class);
    //        
    //final Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJacksonJson());
    try {
        queryGenerator = (QueryGeneratorApi) Class.forName(partnerConfiguration.queryGeneratorClass)
                .newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        // TODO add logger!
        log.log(Level.INFO, "Error getting Query Generator", e);

    }

    String query = getQueryGenerator().toQuery(userProfile);
    long start = System.currentTimeMillis();

    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("query", URLParamEncoder.encode(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);
    String httpJSONResult = httpGet(searchRequest, new HashMap<String, String>() {
        /**
        * 
        */
        private static final long serialVersionUID = -5911519512191023737L;

        {
            put("Authorization", "OAuth oauth_consumer_key=\"" + key + "\"");
            //                put("Accept", "application/xml");
            put("Accept", "application/json");

        }
    });
    log.info(httpJSONResult); // print results
    //ObjectMapper mapper = new ObjectMapper();
    //DDBResponse ddbResponse = mapper.readValue(httpJSONResult, DDBResponse.class);

    /*
            JAXBContext jaxbContext = JAXBContext.newInstance(DDBDocument.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            ZBWDocument zbwResponse = (DDBDocument) jaxbUnmarshaller.unmarshal(respStringReader);
            for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
               try{
    */
    /*
    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);
    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;
       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);
          } catch (EEXCESSDataTransformationException e) {
             logger.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) {
       logger.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(httpJSONResult);
    } 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;

}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.Plug.java

/**
 * @return the value of the {@link #strng variable string} after all
 * instances of ${key} where an entry for "key" exists in the map are
 * replaced with the corresponding value from the map.
 *//*from w w  w.j  a v  a  2s .co  m*/
public String get() {
    return StrSubstitutor.replace(strng, map);
}

From source file:at.bestsolution.fxide.jdt.maven.MavenModuleTypeService.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[2];

    {/*from w  w w.  j av a2  s .c o  m*/
        ICommand cmd = description.newCommand();
        cmd.setBuilderName(JavaCore.BUILDER_ID);
        commands[0] = cmd;
    }

    {
        ICommand cmd = description.newCommand();
        cmd.setBuilderName("org.eclipse.m2e.core.maven2Builder");
        commands[1] = cmd;
    }

    if (resource != null) {
        // If we get a parent path we create a nested project
        try {
            if (resource.getProject().getNature("org.eclipse.m2e.core.maven2Nature") != null) {
                IFolder folder = resource.getProject().getFolder(project.getName());
                if (folder.exists()) {
                    return Status.status(State.ERROR, -1, "Folder already exists", null);
                }
                folder.create(true, true, null);

                description.setLocation(folder.getLocation());
            }
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return Status.status(State.ERROR, -1, "Could not create parent relation", e1);
        }
    }

    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").append("classes")).create(true, true, null);

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

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

        project.getFolder(new Path("src").append("main")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("resources")).create(true, true, null);

        project.getFolder(new Path("src").append("test")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("resources")).create(true, true, null);

        {
            IFile file = project.getFile(new Path("pom.xml"));
            try (InputStream templateStream = getClass().getResourceAsStream("template-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");

                file.create(new ByteArrayInputStream(StrSubstitutor.replace(pomContent, map).getBytes()), true,
                        null);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        IJavaProject jProject = JavaCore.create(project);
        jProject.setOutputLocation(project.getFolder(new Path("target").append("classes")).getFullPath(), null);

        List<IClasspathEntry> entries = new ArrayList<>();

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[2];
            attributes[0] = JavaCore.newClasspathAttribute("optional", "true");
            attributes[1] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("main").append("java");
            IPath output = new Path("target").append("classes");
            IClasspathEntry sourceEntry = JavaCore.newSourceEntry(
                    project.getProject().getFullPath().append(path), null, null,
                    project.getProject().getFullPath().append(output), attributes);
            entries.add(sourceEntry);
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("main").append("resources");
            IPath output = new Path("target").append("classes");
            IPath[] exclusions = new IPath[] { new Path("**") };
            entries.add(JavaCore.newSourceEntry(project.getProject().getFullPath().append(path), null,
                    exclusions, project.getProject().getFullPath().append(output), attributes));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[2];
            attributes[0] = JavaCore.newClasspathAttribute("optional", "true");
            attributes[1] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("test").append("java");
            IPath output = new Path("target").append("test-classes");
            IClasspathEntry sourceEntry = JavaCore.newSourceEntry(
                    project.getProject().getFullPath().append(path), null, null,
                    project.getProject().getFullPath().append(output), attributes);
            entries.add(sourceEntry);
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("test").append("resources");
            IPath output = new Path("target").append("test-classes");
            IPath[] exclusions = new IPath[] { new Path("**") };
            entries.add(JavaCore.newSourceEntry(project.getProject().getFullPath().append(path), null,
                    exclusions, project.getProject().getFullPath().append(output), attributes));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");

            IPath path = JavaRuntime.newDefaultJREContainerPath();
            entries.add(JavaCore.newContainerEntry(path, null, attributes, false));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");

            IPath path = new Path("org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER");
            entries.add(JavaCore.newContainerEntry(path, null, attributes, false));
        }

        jProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), null);
        project.getWorkspace().save(true, null);
        return Status.ok();
    } catch (CoreException ex) {
        //TODO
        ex.printStackTrace();
        return Status.status(State.ERROR, -1, "Failed to create project", ex);
    }
}

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

protected MendeleyResponse fetchSearchResults(Client client, SecureUserProfile userProfile,
        AccessTokenResponse accessTokenResponse, PartnerConfiguration partnerConfiguration)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    String query = PartnerConfigurationEnum.CONFIG.getQueryGenerator().toQuery(userProfile);
    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("query", URLParamEncoder.encode(query));
    String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);
    MendeleyResponse jsonResponse = getJSONResponse(client, accessTokenResponse, searchRequest);

    if (jsonResponse == null || jsonResponse.getDocuments() == null)
        log.log(Level.WARNING, "Mendeley returned an empty result list");

    int numResults = 100;
    if (userProfile.numResults != null)
        numResults = userProfile.numResults;

    jsonResponse.limitNumDocuments(numResults);

    return jsonResponse;
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.Plug.java

/** 
 * Gets the value of the {@link #strng variable string} after all
 * instances of ${key} where an entry for "key" exists in the map are
 * replaced with the corresponding value from the map. Also writes the 
 * string to a file using UTF-8 encoding.
 * @param pathToFile {@link java.nio.file.Path Path} to write the string to.
 * @param append boolean, if true string will be appended to file rather than
 * overwriting it.//from ww  w . j a  v a  2 s. com
 * @return The same string written to the file, in case you want it for 
 * anything
 * @throws Exception on error creating or writing to file.
 */
public String get(Path pathToFile, boolean append) throws Exception {
    String out = StrSubstitutor.replace(strng, map);
    FileUtils.writeStringToFile(pathToFile.toFile(), out, "UTF-8", append);
    return out;
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.Plug.java

/** 
 * Gets the value of the {@link #strng variable string} after all
 * instances of ${key} where an entry for "key" exists in the map are
 * replaced with the corresponding value from the map. Also writes the 
 * string to a file using UTF-8 encoding.
 * @param file {@link java.io.File File} to write the string to.
 * @param append boolean, if true string will be appended to file rather than
 * overwriting it.//  w  w  w .  j  ava2  s.c  o m
 * @return The same string written to the file, in case you want it for 
 * anything
 * @throws Exception on error creating or writing to file.
 */
public String get(File file, boolean append) throws Exception {
    String out = StrSubstitutor.replace(strng, map);
    FileUtils.writeStringToFile(file, out, "UTF-8", append);
    return out;
}

From source file:com.qmetry.qaf.automation.step.client.CustomStep.java

@SuppressWarnings({ "unchecked" })
public void processStepParams() {
    // process parameters in step;
    if ((actualArgs != null) && (actualArgs.length > 0)) {
        Map<String, Object> paramMap = getStepExecutionTracker().getContext();
        List<String> paramNames = BDDDefinitionHelper.getArgNames(def);

        System.out.println(paramNames);
        for (int i = 0; i < actualArgs.length; i++) {
            String paramName = paramNames.get(i).trim();
            // remove starting { and ending } from parameter name
            paramName = paramName.substring(1, paramName.length() - 1).split(":", 2)[0];

            // in case of data driven test args[0] should not be overriden
            // with steps args[0]
            if ((actualArgs[i] instanceof String)) {

                String pstr = (String) actualArgs[i];

                if (pstr.startsWith("${") && pstr.endsWith("}")) {
                    String pname = pstr.substring(2, pstr.length() - 1);
                    actualArgs[i] = paramMap.containsKey(pstr) ? paramMap.get(pstr)
                            : paramMap.containsKey(pname) ? paramMap.get(pname)
                                    : getBundle().containsKey(pstr) ? getBundle().getObject(pstr)
                                            : getBundle().getObject(pname);
                } else if (pstr.indexOf("$") >= 0) {
                    pstr = getBundle().getSubstitutor().replace(pstr);
                    actualArgs[i] = StrSubstitutor.replace(pstr, paramMap);
                }/*from  w  w w  .  j a va  2s .c om*/
                // continue;
                ParamType ptype = ParamType.getType(pstr);
                if (ptype.equals(ParamType.MAP)) {
                    Map<String, Object> kv = new Gson().fromJson(pstr, Map.class);
                    paramMap.put(paramName, kv);
                    for (String key : kv.keySet()) {
                        paramMap.put(paramName + "." + key, kv.get(key));
                    }
                } else if (ptype.equals(ParamType.LIST)) {
                    List<Object> lst = new Gson().fromJson(pstr, List.class);
                    paramMap.put(paramName, lst);
                    for (int li = 0; li < lst.size(); li++) {
                        paramMap.put(paramName + "[" + li + "]", lst.get(li));
                    }
                }
            }

            paramMap.put("${args[" + i + "]}", actualArgs[i]);
            paramMap.put("args[" + i + "]", actualArgs[i]);
            paramMap.put(paramName, actualArgs[i]);

        }

        description = StrSubstitutor.replace(description, paramMap);

        for (TestStep step : steps) {
            ((StringTestStep) step).initStep();
            if ((step.getActualArgs() != null) && (step.getActualArgs().length > 0)) {
                for (int j = 0; j < step.getActualArgs().length; j++) {

                    if (paramMap.containsKey(step.getActualArgs()[j])) {
                        step.getActualArgs()[j] = paramMap.get(step.getActualArgs()[j]);
                    } else {
                        step.getActualArgs()[j] = StrSubstitutor.replace(step.getActualArgs()[j], paramMap);
                    }

                }
            } else if (step.getName().indexOf("$") >= 0) {
                // bdd?
                String name = StrSubstitutor.replace(step.getName(), paramMap);

                ((BaseTestStep) step).setName(name);
            }
        }
    }
}

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

protected EuropeanaDocDetail fetchDocumentDetails(String objectId, PartnerConfiguration partnerConfiguration,
        String eexcessRequestId) throws EEXCESSDataTransformationException {
    try {/*from ww w .j  ava2  s.  c  o m*/
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJacksonJson());
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("objectId", objectId);
        valuesMap.put("apiKey", partnerConfiguration.apiKey);
        String detailEndpoint = "http://europeana.eu/api/v2/record/${objectId}.json?wskey=${apiKey}";
        String detailRequest = StrSubstitutor.replace(detailEndpoint, valuesMap);
        WebResource service = client.resource(detailRequest);
        Builder builder = service.accept(MediaType.APPLICATION_JSON);
        EuropeanaDocDetail jsonResponse = builder.get(EuropeanaDocDetail.class);
        PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, jsonResponse.toString(),
                "detail-response", PartnerdataTracer.FILETYPE.JSON, eexcessRequestId);
        client.destroy();
        return jsonResponse;
    } catch (Exception e) {
        throw new EEXCESSDataTransformationException(e);
    }
}

From source file:com.qmetry.qaf.automation.step.JavaStep.java

protected Object[] processArgs(Method method, Object... objects) {
    int noOfParams = method.getParameterTypes().length;
    if (noOfParams == 0) {
        return null;
    }//from ww  w.j  a  va 2  s.c  o  m
    Object[] params = new Object[noOfParams];
    Map<String, Object> context = getStepExecutionTracker().getContext();

    try {
        if ((noOfParams == (objects.length - 1)) && method.getParameterTypes()[noOfParams - 1].isArray()) {
            // case of optional arguments!...
            System.arraycopy(objects, 0, params, 0, objects.length);
            params[noOfParams - 1] = "[]";
        } else {
            System.arraycopy(objects, 0, params, 0, noOfParams);
        }
    } catch (Exception e) {
        throw new RuntimeException("Wrong number of parameters, Expected " + noOfParams
                + " parameters but Actual is " + (objects == null ? "0" : objects.length));
    }
    Gson gson = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    description = StrSubstitutor.replace(description, context);
    description = getBundle().getSubstitutor().replace(description);
    for (int i = 0; i < noOfParams; i++) {

        if ((params[i] instanceof String)) {
            String pstr = (String) params[i];

            if (pstr.startsWith("${") && pstr.endsWith("}")) {
                String pname = pstr.substring(2, pstr.length() - 1);
                params[i] = context.containsKey(pstr) ? context.get(pstr)
                        : context.containsKey(pname) ? context.get(pname)
                                : getBundle().containsKey(pstr) ? getBundle().getObject(pstr)
                                        : getBundle().getObject(pname);
            } else if (pstr.indexOf("$") >= 0) {
                pstr = getBundle().getSubstitutor().replace(pstr);
                params[i] = StrSubstitutor.replace(pstr, context);
            }

        }
        Class<?> paramType = method.getParameterTypes()[i];
        if (String.class.isAssignableFrom(paramType)) {
            continue;
        }
        try {
            String strVal = gson.toJson(params[i]);
            if (params[i] instanceof String) {
                strVal = String.valueOf(params[i]);
            }

            strVal = getBundle().getSubstitutor().replace(strVal);
            strVal = StrSubstitutor.replace(strVal, context);
            Object o = gson.fromJson(strVal, paramType);
            params[i] = o;
        } catch (Exception e) {
        }
    }

    return params;
}