Example usage for java.util.regex Matcher quoteReplacement

List of usage examples for java.util.regex Matcher quoteReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher quoteReplacement.

Prototype

public static String quoteReplacement(String s) 

Source Link

Document

Returns a literal replacement String for the specified String .

Usage

From source file:org.muse.mneme.impl.ImportServiceImpl.java

/**
 * Create a fillin question from Samigo data.
 * //from   w  w  w.j a  va 2 s .  c  o  m
 * @param these
 *        The Samigo data entries.
 * @param pool
 *        The pool for the question.
 * @param text
 *        true if text, false if numeric.
 * @return The question, or null if it was not made
 * @throws AssessmentPermissionException
 */
protected Question createFillin(SamigoQuestion[] these, String attachments, Pool pool, boolean text)
        throws AssessmentPermissionException {
    // validate: fist questionChoiceText for the question text not null
    boolean valid = (these[0].questionChoiceText != null);

    // answerMatchText from all for the choices not null
    if (valid) {
        for (int index = 0; index < these.length; index++) {
            if (these[index].answerMatchText == null) {
                valid = false;
                break;
            }
        }
    }

    if (!valid) {
        M_log.info("createFillin: invalid samigo question: " + these[0].itemId);
        return null;
    }

    // create the question
    Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks");
    FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion());

    // detect these[0].exclusive and translate to our "any order"
    f.setAnyOrder(Boolean.FALSE.toString());
    if ((these[0].exclusive != null) && (these[0].exclusive.booleanValue())) {
        // if we find that all the fill-in correct patterns are the same,
        // and there are is one for each answer (comma separated),
        // spread them out, one per fill-in, and set any-order
        boolean mutualExclusive = true;
        for (int index = 1; index < these.length; index++) {
            if (!these[index].answerMatchText.equals(these[0].answerMatchText)) {
                mutualExclusive = false;
                break;
            }
        }

        if (mutualExclusive) {
            String[] parts = these[0].answerMatchText.split("\\|");
            if ((parts != null) && (parts.length == these.length)) {
                for (int index = 0; index < these.length; index++) {
                    these[index].answerMatchText = parts[index];
                }

                f.setAnyOrder(Boolean.TRUE.toString());
            }
        }
    }

    // case sensitive
    if (these[0].caseSensitive != null)
        f.setCaseSensitive(these[0].caseSensitive.toString());

    // text or numeric
    f.setResponseTextual(Boolean.toString(text));

    // recreate the text, fillin in the "{}" with these answerMatchText

    String questionText = these[0].questionChoiceText;
    for (int index = 0; index < these.length; index++) {
        questionText = questionText.replaceFirst("\\{\\}",
                Matcher.quoteReplacement("{" + these[index].answerMatchText + "}"));
    }

    // set the text
    String clean = HtmlHelper.clean(questionText + attachments);
    f.setText(clean);

    return question;
}

From source file:net.sourceforge.pmd.docs.RuleDocGenerator.java

private String getRuleClassSourceFilepath(String ruleClass) throws IOException {
    final String relativeSourceFilename = ruleClass.replaceAll("\\.", Matcher.quoteReplacement(File.separator))
            + ".java";
    final List<Path> foundPathResult = new LinkedList<>();

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override/*from  w  w w. j  ava 2  s. co  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String path = file.toString();
            if (path.contains("src") && path.endsWith(relativeSourceFilename)) {
                foundPathResult.add(file);
                return FileVisitResult.TERMINATE;
            }
            return super.visitFile(file, attrs);
        }
    });

    if (!foundPathResult.isEmpty()) {
        Path foundPath = foundPathResult.get(0);
        foundPath = root.relativize(foundPath);
        return FilenameUtils.normalize(foundPath.toString(), true);
    }

    return FilenameUtils.normalize(relativeSourceFilename, true);
}

From source file:com.buaa.cfs.utils.StringUtils.java

/**
 * Matches a template string against a pattern, replaces matched tokens with the supplied replacements, and returns
 * the result.  The regular expression must use a capturing group.  The value of the first capturing group is used
 * to look up the replacement.  If no replacement is found for the token, then it is replaced with the empty
 * string.//from   w  ww . j  ava  2 s  .co m
 * <p>
 * For example, assume template is "%foo%_%bar%_%baz%", pattern is "%(.*?)%", and replacements contains 2 entries,
 * mapping "foo" to "zoo" and "baz" to "zaz".  The result returned would be "zoo__zaz".
 *
 * @param template     String template to receive replacements
 * @param pattern      Pattern to match for identifying tokens, must use a capturing group
 * @param replacements Map<String, String> mapping tokens identified by the capturing group to their replacement
 *                     values
 *
 * @return String template with replacements
 */
public static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
        String replacement = replacements.get(matcher.group(1));
        if (replacement == null) {
            replacement = "";
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.apache.nifi.processors.standard.ReplaceText.java

/**
 * If we have a '$' followed by anything other than a number, then escape
 * it. E.g., '$d' becomes '\$d' so that it can be used as a literal in a
 * regex.//w w  w  . ja  v a2 s  . com
 */
private static String normalizeReplacementString(String replacement) {
    String replacementFinal = replacement;
    if (REPLACEMENT_NORMALIZATION_PATTERN.matcher(replacement).find()) {
        replacementFinal = Matcher.quoteReplacement(replacement);
    }
    return replacementFinal;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Generates and saves info.xml//from   w w  w . j  av a2 s .co  m
 *
 * @param path
 * @param mets
 */
public static void saveInfoFile(String path, MetsContext metsContext, String md5, String fileMd5Name,
        File metsFile) throws MetsExportException {
    File infoFile = new File(path + File.separator + metsContext.getPackageID() + File.separator + "info_"
            + metsContext.getPackageID() + ".xml");
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date());
    XMLGregorianCalendar date2;
    try {
        date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e1) {
        throw new MetsExportException("Error while generating info.xml file", false, e1);
    }
    Info infoJaxb = new Info();
    infoJaxb.setCreated(date2);
    infoJaxb.setMainmets("./" + metsFile.getName());
    Checksum checkSum = new Checksum();
    checkSum.setChecksum(md5);
    checkSum.setType("MD5");
    addModsIdentifiersRecursive(metsContext.getRootElement(), infoJaxb);
    checkSum.setValue(fileMd5Name);
    infoJaxb.setChecksum(checkSum);
    Validation validation = new Validation();
    validation.setValue("W3C-XML");
    validation.setVersion(Float.valueOf("0.0"));
    infoJaxb.setValidation(validation);
    infoJaxb.setCreator(metsContext.getCreatorOrganization());
    infoJaxb.setPackageid(metsContext.getPackageID());
    if (Const.PERIODICAL_TITLE.equalsIgnoreCase(metsContext.getRootElement().getElementType())) {
        infoJaxb.setMetadataversion((float) 1.5);
    } else {
        infoJaxb.setMetadataversion((float) 1.1);
    }
    Itemlist itemList = new Itemlist();
    infoJaxb.setItemlist(itemList);
    itemList.setItemtotal(BigInteger.valueOf(metsContext.getFileList().size()));
    List<FileMD5Info> fileList = metsContext.getFileList();
    long size = 0;
    for (FileMD5Info fileName : fileList) {
        itemList.getItem()
                .add(fileName.getFileName().replaceAll(Matcher.quoteReplacement(File.separator), "/"));
        size += fileName.getSize();
    }
    int infoTotalSize = (int) (size / 1024);
    infoJaxb.setSize(infoTotalSize);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        // SchemaFactory factory =
        // SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // factory.setResourceResolver(MetsLSResolver.getInstance());
        // Schema schema = factory.newSchema(new
        // StreamSource(Info.class.getResourceAsStream("info.xsd")));
        // marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.marshal(infoJaxb, infoFile);
    } catch (Exception ex) {
        throw new MetsExportException("Error while generating info.xml", false, ex);
    }

    List<String> validationErrors;
    try {
        validationErrors = MetsUtils.validateAgainstXSD(infoFile, Info.class.getResourceAsStream("info.xsd"));
    } catch (Exception e) {
        throw new MetsExportException("Error while validating info.xml", false, e);
    }

    if (validationErrors.size() > 0) {
        MetsExportException metsException = new MetsExportException(
                "Invalid info file:" + infoFile.getAbsolutePath(), false, null);
        metsException.getExceptions().get(0).setValidationErrors(validationErrors);
        for (String error : validationErrors) {
            LOG.fine(error);
        }
        throw metsException;
    }
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Process the custom path list and create .cmf files for each folder path using the template folders that come with PDTool.
 * /*  ww  w . j  ava 2  s .  c om*/
 * @param customPathList
 * @param templateFolderPath
 * @param forceCopy
 * @param toFilePath
 */
public static void processTemplateFolder(String customPathList, String templateFolderPath, String toFilePath,
        boolean forceCopy) {

    // Initialize variables.
    String templateSharedFolder = getFileAsString(templateFolderPath + "/sharedFolder.cmf");
    String templateVirtualFolder = getFileAsString(templateFolderPath + "/virtualFolder.cmf");
    String templateDatabase = getFileAsString(templateFolderPath + "/database.cmf");
    String templateCatalog = getFileAsString(templateFolderPath + "/catalog.cmf");
    String templateSchema = getFileAsString(templateFolderPath + "/schema.cmf");
    String templateText = null;
    String pathStart = null;
    String remainderPath = null;
    String resourcePath = null;
    String resourcePathEncoded = null;
    String resourceName = null;
    String resourceNameEncoded = null;
    String fsPath = null;
    BigInteger bigIntTime = null;
    String regexSize = "200000";
    String regexReplacePatternDoubleQuote = "\\,(?=[^\"]{0," + regexSize + "}\"(?:[^\"\\r\\n]{0," + regexSize
            + "}\"[^\"]{0," + regexSize + "}\"){0," + regexSize + "}[^\"\\r\\n]{0," + regexSize + "}$)";

    // Replace commas within double quotes with encoded commas
    customPathList = customPathList.replaceAll(regexReplacePatternDoubleQuote, "_002c");

    // Iterate over the comma separated paths
    StringTokenizer pst = new StringTokenizer(customPathList, ",");
    while (pst.hasMoreTokens()) {
        String token = pst.nextToken();

        // Make sure all paths have forward slashes
        token = token.replaceAll(Matcher.quoteReplacement("\\\\"), "/");
        token = token.replaceAll(Matcher.quoteReplacement("\\"), "/");
        // Make sure all paths have a single forward slash
        token = token.replaceAll("//", "/");
        // Make sure no paths have double quotes
        token = token.replaceAll("\"", "");
        // Replace encoded commas with real commas
        token = token.replaceAll("_002c", ",");

        // Create custom shared folders
        // e.g. /shared/My Folder,/shared/My Folder/My.Folder/My-Folder/""My,Folder""
        pathStart = "/shared/";
        if (token.startsWith(pathStart)) {
            remainderPath = token.replaceFirst(pathStart, "");
            resourcePath = pathStart;
            resourcePathEncoded = pathStart;
            fsPath = toFilePath;

            StringTokenizer st = new StringTokenizer(remainderPath, "/");
            while (st.hasMoreTokens()) {
                resourceName = st.nextToken();
                resourceNameEncoded = ResourceNameCodec.encode(resourceName);
                templateText = templateSharedFolder;

                // CIS resource path
                resourcePath = (resourcePath + "/" + resourceName).replaceAll("//", "/");
                resourcePathEncoded = (resourcePathEncoded + "/" + resourceNameEncoded).replaceAll("//", "/");

                // Files system path
                fsPath = (toFilePath + "/" + resourcePathEncoded).replaceAll("//", "/");
                mkdirs(fsPath);

                /*
                 *  Create File content
                 */
                // Encode name
                resourceName = encodePath(resourceName);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_NAME"),
                        resourceName);

                // Encode path
                resourcePath = encodePath(resourcePath);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_PATH"),
                        resourcePath);

                bigIntTime = TimestampToBigint(getCurrentDateAsString("yyyy-MM-dd HH:mm:ss.SSS"));
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$CREATE_DATE_LONG"),
                        bigIntTime.toString());

                // Decode path
                templateText = decodePath(templateText);

                // Write out the file
                fsPath = fsPath + "/" + resourceNameEncoded + ".cmf";
                boolean fileExists = fileExists(fsPath);
                if (!fileExists) {
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
                if (fileExists && forceCopy) {
                    removeFile(fsPath);
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
            }
        }

        // Create custom database folders
        // e.g. /services/databases/My Database{TYPE:DATABASE}/My.Catalog{TYPE:CATALOG}/My$Schema{TYPE:SCHEMA}
        pathStart = "/services/databases/";
        if (token.startsWith(pathStart)) {
            remainderPath = token.replaceFirst(pathStart, "");
            resourcePath = pathStart;
            resourcePathEncoded = pathStart;
            fsPath = toFilePath;
            int pathCount = 0;

            StringTokenizer st = new StringTokenizer(remainderPath, "/");
            while (st.hasMoreTokens()) {
                token = st.nextToken();
                ++pathCount;

                // Convert square bracket characters to angle bracket characters
                if (token.contains("["))
                    token = token.replace("[", "<");
                if (token.contains("]"))
                    token = token.replace("]", ">");

                // If this is the first path extracted then assume it is a database token
                if (pathCount == 1)
                    templateText = templateDatabase;

                // Determine if the token is a database type token: "/services/databases/My Database[TYPE=DATABASE]/My Catalog[type=catalog]/My Schema[Type=Schema]"
                if (token.toUpperCase().trim().contains("<TYPE=DATABASE>")) {
                    int beg = token.toUpperCase().indexOf("<");
                    int end = token.toUpperCase().indexOf(">");
                    resourceName = token.substring(0, beg);
                    if (end + 1 < token.length())
                        resourceName = resourceName + token.substring(end + 1);
                    templateText = templateDatabase;
                }
                // Determine if the token is a catalog type token: "/services/databases/My Database[TYPE=DATABASE]/My Catalog[type=catalog]/My Schema[Type=Schema]"
                else if (token.toUpperCase().trim().contains("<TYPE=CATALOG>")) {
                    int beg = token.toUpperCase().indexOf("<");
                    int end = token.toUpperCase().indexOf(">");
                    resourceName = token.substring(0, beg);
                    if (end + 1 < token.length())
                        resourceName = resourceName + token.substring(end + 1);
                    templateText = templateCatalog;
                }
                // Determine if the token is a schema type token: "/services/databases/My Database[TYPE=DATABASE]/My Catalog[type=catalog]/My Schema[Type=Schema]"
                else if (token.toUpperCase().trim().contains("<TYPE=SCHEMA>")) {
                    int beg = token.toUpperCase().indexOf("<");
                    int end = token.toUpperCase().indexOf(">");
                    resourceName = token.substring(0, beg);
                    if (end + 1 < token.length())
                        resourceName = resourceName + token.substring(end + 1);
                    templateText = templateSchema;
                    // Otherwise default to a folder token
                } else {
                    resourceName = token;
                    templateText = templateVirtualFolder;
                }
                resourceNameEncoded = ResourceNameCodec.encode(resourceName);

                // CIS resource path
                resourcePath = (resourcePath + "/" + resourceName).replaceAll("//", "/");
                resourcePathEncoded = (resourcePathEncoded + "/" + resourceNameEncoded).replaceAll("//", "/");

                // Files system path
                fsPath = (toFilePath + "/" + resourcePathEncoded).replaceAll("//", "/");
                mkdirs(fsPath);

                /*
                 *  Create File content
                 */
                // Encode name
                resourceName = encodePath(resourceName);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_NAME"),
                        resourceName);

                // Encode path
                resourcePath = encodePath(resourcePath);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_PATH"),
                        resourcePath);

                bigIntTime = TimestampToBigint(getCurrentDateAsString("yyyy-MM-dd HH:mm:ss.SSS"));
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$CREATE_DATE_LONG"),
                        bigIntTime.toString());

                // Decode path
                templateText = decodePath(templateText);

                // Write out the file
                fsPath = fsPath + "/" + resourceNameEncoded + ".cmf";
                boolean fileExists = fileExists(fsPath);
                if (!fileExists) {
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
                if (fileExists && forceCopy) {
                    removeFile(fsPath);
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
            }
        }

        // Create custom web services folders
        // e.g. /services/webservices/My Folder/My.Folder/My-Folder
        pathStart = "/services/webservices/";
        if (token.startsWith(pathStart)) {
            remainderPath = token.replaceFirst(pathStart, "");
            resourcePath = pathStart;
            resourcePathEncoded = pathStart;
            fsPath = toFilePath;

            StringTokenizer st = new StringTokenizer(remainderPath, "/");
            while (st.hasMoreTokens()) {
                resourceName = st.nextToken();
                resourceNameEncoded = ResourceNameCodec.encode(resourceName);
                templateText = templateVirtualFolder;

                // CIS resource path
                resourcePath = (resourcePath + "/" + resourceName).replaceAll("//", "/");
                resourcePathEncoded = (resourcePathEncoded + "/" + resourceNameEncoded).replaceAll("//", "/");

                // Files system path
                fsPath = (toFilePath + "/" + resourcePathEncoded).replaceAll("//", "/");
                mkdirs(fsPath);

                /*
                 *  Create File content
                 */
                // Encode name
                resourceName = encodePath(resourceName);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_NAME"),
                        resourceName);

                // Encode path
                resourcePath = encodePath(resourcePath);
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$RESOURCE_PATH"),
                        resourcePath);

                bigIntTime = TimestampToBigint(getCurrentDateAsString("yyyy-MM-dd HH:mm:ss.SSS"));
                templateText = templateText.replaceAll(Matcher.quoteReplacement("$CREATE_DATE_LONG"),
                        bigIntTime.toString());

                // Decode path
                templateText = decodePath(templateText);

                // Write out the file
                fsPath = fsPath + "/" + resourceNameEncoded + ".cmf";
                boolean fileExists = fileExists(fsPath);
                if (!fileExists) {
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
                if (fileExists && forceCopy) {
                    removeFile(fsPath);
                    CommonUtils.createFileWithContent(fsPath, templateText);
                }
            }
        }
    }
}

From source file:com.cisco.dvbu.ps.deploytool.services.ResourceCacheManagerImpl.java

public void generateResourceCacheXML(String serverId, String startPath, String pathToResourceCacheXML,
        String pathToServersXML, String options) throws CompositeException {

    // Set the command and action name
    String command = "generateResourceCacheXML";
    String actionName = "CREATE_XML";

    // Validate whether the files exist or not
    if (!CommonUtils.fileExists(pathToServersXML)) {
        throw new CompositeException("File [" + pathToServersXML + "] does not exist.");
    }/*  w w  w . j a  v  a  2  s  .com*/

    // Set the Module Action Objective
    String s1 = (startPath == null) ? "no_startPath" : "Path=" + startPath;
    System.setProperty("MODULE_ACTION_OBJECTIVE", "GENERATE : " + s1);

    String prefix = "generateResourceCacheXML";
    // Get the configuration property file set in the environment with a default of deploy.properties
    String propertyFile = CommonUtils.getFileOrSystemPropertyValue(CommonConstants.propertyFile,
            "CONFIG_PROPERTY_FILE");
    // Extract any variables from the startPath
    startPath = CommonUtils.extractVariable(prefix, startPath, propertyFile, true);

    // Prepare a local ResourceCacheModule XML variable for creating a list of "ResourceCache" nodes
    // This XML variable will be written out to the specified file. 
    ResourceCacheModule resourceCacheModule = new ObjectFactory().createResourceCacheModule();

    // Use the options list to set boolean variables for getting resources based on TABLE,PROCEDURE,CONFIGURED and NONCONFIGURED
    Boolean getResourceType_TABLE = false;
    Boolean getResourceType_PROCDURE = false;
    Boolean getConfigured = false;
    Boolean getNonConfigured = false;
    String filter = null;
    // If the options field is null or empty the default is to get both resource types and both configured and non-configured resource cache types
    if (options == null || options.isEmpty() || options.equalsIgnoreCase("")) {
        // TABLE and PROCEDURE are the valid resource types that can have caching configured
        getResourceType_TABLE = true;
        getResourceType_PROCDURE = true;
        getConfigured = true;
        getNonConfigured = true;
    } else {
        // Insure there are no spaces on the end and replace any space in between with commas to insure a comma separated list
        options = options.trim().replaceAll(Matcher.quoteReplacement(" "), ",");
        StringTokenizer st = new StringTokenizer(options, ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.equalsIgnoreCase("TABLE")) {
                getResourceType_TABLE = true;
                filter = "TABLE";
            }
            if (token.equalsIgnoreCase("PROCEDURE")) {
                getResourceType_PROCDURE = true;
                if (filter == null) {
                    filter = "PROCEDURE";
                } else {
                    filter = filter + ",PROCEDURE";
                }
            }
            if (token.equalsIgnoreCase("CONFIGURED")) {
                getConfigured = true;
            }
            if (token.equalsIgnoreCase("NONCONFIGURED")) {
                getNonConfigured = true;
            }
        }
        // If neither TABLE or PROCEDURE is found the default is to get both resource types
        if (!getResourceType_TABLE && !getResourceType_PROCDURE) {
            getResourceType_TABLE = true;
            getResourceType_PROCDURE = true;
            filter = "TABLE,PROCEDURE";
        }
        // If neither CONFIGURED or NONCONFIGURED is found the default is to get both configured and non-configured cache resources
        if (!getConfigured && !getNonConfigured) {
            getConfigured = true;
            getNonConfigured = true;
        }
    }

    // Retrieve the list of Resources by invoking the CIS Web Service API
    ResourceList resourceList = new ResourceList();

    if (getResourceType_TABLE) {
        resourceList.getResource()
                .addAll(DeployManagerUtil.getDeployManager().getResourcesFromPath(serverId, startPath,
                        ResourceType.CONTAINER.name(), filter, DetailLevel.FULL.name(), pathToServersXML)
                        .getResource());
    }

    // Continue if there is a list
    if (resourceList != null && resourceList.getResource() != null && !resourceList.getResource().isEmpty()) {

        // Don't validate the resource exists since the paths have already been acquired from the server.
        Boolean validateResourceExists = false;

        // Assign the list of resources to a local Attribute type variable
        List<Resource> resources = resourceList.getResource();

        // Iterate over the retrieved Server Attribute List
        for (Resource resource : resources) {
            // Define the resource cache type
            ResourceCacheType resourceCacheType = new ResourceCacheType();

            // Set the resource path
            resourceCacheType.setResourcePath(resource.getPath());
            // Set the resource type
            resourceCacheType.setResourceType(ResourceTypeSimpleType.valueOf(resource.getType().toString()));

            // Get the resource cache configuration from the CIS server for a given path and type
            CacheConfig cacheConfig = getResourceCacheDAO().getResourceCacheConfig(resource.getPath(),
                    resource.getType().toString(), serverId, pathToServersXML, validateResourceExists);

            if (cacheConfig != null) {
                // Define the resource cache config type
                ResourceCacheConfigType resourceCacheConfigType = new ResourceCacheConfigType();

                // Set the cache configured element
                resourceCacheConfigType.setConfigured(cacheConfig.isConfigured());

                // Only set cacheConfig objects if it is configured
                if (cacheConfig.isConfigured()) {

                    if (cacheConfig.isEnabled() != null) {
                        resourceCacheConfigType.setEnabled(cacheConfig.isEnabled());
                    }
                    if (cacheConfig.getExpirationPeriod() != null) {
                        // Define the calendar period type
                        ResourceCacheCalendarPeriodType calendarPeriod = new ResourceCacheCalendarPeriodType();

                        Period period = new Period();
                        period = period.getCalandarPeriod(cacheConfig.getExpirationPeriod(), "milliseconds");
                        calendarPeriod.setPeriod(period.getPeriod());
                        calendarPeriod.setCount(period.getCount());
                        // Set the expiration period
                        resourceCacheConfigType.setExpirationPeriod(calendarPeriod);
                    }
                    if (cacheConfig.getClearRule() != null) {
                        resourceCacheConfigType.setClearRule(cacheConfig.getClearRule().toString());
                    }

                    if (cacheConfig.getRefresh() != null) {
                        // Define the resource refresh type
                        ResourceCacheRefreshType resourceCacheRefreshType = new ResourceCacheRefreshType();

                        // Modes: MANUAL or SCHEDULED
                        if (cacheConfig.getRefresh().getMode() != null) {
                            resourceCacheRefreshType.setMode(cacheConfig.getRefresh().getMode().toString());
                        }

                        // Continue if not null and the mode is SCHEDULED -- no need to print out a schedule if MANUAL
                        if (cacheConfig.getRefresh().getSchedule() != null) {
                            if (cacheConfig.getRefresh().getMode().toString().equalsIgnoreCase("SCHEDULED")) {
                                // Define the resource refresh schedule
                                ResourceCacheRefreshScheduleType resourceCacheRefreshScheduleType = new ResourceCacheRefreshScheduleType();

                                if (cacheConfig.getRefresh().getSchedule().getStartTime() != null) {
                                    resourceCacheRefreshScheduleType.setStartTime(
                                            cacheConfig.getRefresh().getSchedule().getStartTime());
                                }

                                if (cacheConfig.getRefresh().getSchedule().getMode().toString()
                                        .equalsIgnoreCase("INTERVAL")) {
                                    // Define the calendar period type
                                    ResourceCacheCalendarPeriodType calendarPeriod = new ResourceCacheCalendarPeriodType();

                                    if (cacheConfig.getRefresh().getSchedule().getInterval() != null) {
                                        Period period = new Period();
                                        period = period.getCalandarPeriod(cacheConfig.getExpirationPeriod(),
                                                "seconds");
                                        calendarPeriod.setPeriod(period.getPeriod());
                                        calendarPeriod.setCount(period.getCount());
                                        // Set the refresh period
                                        resourceCacheRefreshScheduleType.setRefreshPeriod(calendarPeriod);
                                    }
                                }

                                if (cacheConfig.getRefresh().getSchedule().getMode().toString()
                                        .equalsIgnoreCase("CALENDAR")) {
                                    // Define the calendar period type
                                    ResourceCacheCalendarPeriodType calendarPeriod = new ResourceCacheCalendarPeriodType();

                                    if (cacheConfig.getRefresh().getSchedule().getPeriod() != null) {
                                        calendarPeriod.setPeriod(
                                                cacheConfig.getRefresh().getSchedule().getPeriod().toString());
                                        calendarPeriod
                                                .setCount(cacheConfig.getRefresh().getSchedule().getCount());
                                        // Set the refresh period
                                        resourceCacheRefreshScheduleType.setRefreshPeriod(calendarPeriod);
                                    }
                                }
                                // set the resource cache refresh schedule
                                resourceCacheRefreshType.setSchedule(resourceCacheRefreshScheduleType);
                            }
                        }
                        // set the resource refresh
                        resourceCacheConfigType.setRefresh(resourceCacheRefreshType);
                    }

                    if (cacheConfig.getStorage() != null) {
                        // Define the resource storage type
                        ResourceCacheStorageType resourceCacheStorageType = new ResourceCacheStorageType();

                        if (cacheConfig.getStorage().getMode() != null) {
                            resourceCacheStorageType.setMode(cacheConfig.getStorage().getMode().toString());
                        }
                        if (cacheConfig.getStorage().getStorageDataSourcePath() != null) {
                            resourceCacheStorageType.setStorageDataSourcePath(
                                    cacheConfig.getStorage().getStorageDataSourcePath());
                        }

                        if (cacheConfig.getStorage().getStorageTargets() != null) {
                            // Define the storage target type
                            ResourceCacheStorageTargetsType entry = new ResourceCacheStorageTargetsType();

                            for (TargetPathTypePair storageTarget : cacheConfig.getStorage().getStorageTargets()
                                    .getEntry()) {
                                // Set the storage target entry
                                entry.setPath(storageTarget.getPath());
                                entry.setTargetName(storageTarget.getTargetName());
                                entry.setType(storageTarget.getType().toString());
                                resourceCacheStorageType.getStorageTargets().add(entry);
                            }
                        }
                        // Set the resource storage type
                        resourceCacheConfigType.setStorage(resourceCacheStorageType);
                    }
                }
                // Set the resource cache configuration
                resourceCacheType.setCacheConfig(resourceCacheConfigType);

                // Add an XML node if the resource is configured for cache and the user is requesting CONFIGURED
                if (cacheConfig.isConfigured() && getConfigured) {
                    // Set basic values for Id, Path and Type               
                    resourceCacheType.setId(getTokenId("cache"));

                    // Add a new row to the XML for Resource Cache
                    resourceCacheModule.getResourceCache().add(resourceCacheType);
                }
                // Add an XML node if the resource is not configured for cache and the user is requesting NONCONFIGURED
                if (!cacheConfig.isConfigured() && getNonConfigured) {
                    // Set basic values for Id, Path and Type
                    resourceCacheType.setId(getTokenId("cache"));

                    // Add a new row to the XML for Resource Cache
                    resourceCacheModule.getResourceCache().add(resourceCacheType);
                }
            }
        }
    }

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        // Generate the XML file
        XMLUtils.createXMLFromModuleType(resourceCacheModule, pathToResourceCacheXML);
    } else {
        logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                + "] WAS NOT PERFORMED.\n");
    }
}

From source file:org.openbravo.erpCommon.utility.reporting.printing.PrintController.java

void sendDocumentEmail(Report report, VariablesSecureApp vars, Vector<Object> object, PocData documentData,
        String senderAddress, HashMap<String, Boolean> checks, DocumentType documentType)
        throws IOException, ServletException {
    final String attachmentFileLocation = report.getTargetLocation();
    String emailSubject = null, emailBody = null;
    final String ourReference = report.getOurReference();
    final String cusReference = report.getCusReference();
    if (log4j.isDebugEnabled())
        log4j.debug("our document ref: " + ourReference);
    if (log4j.isDebugEnabled())
        log4j.debug("cus document ref: " + cusReference);

    final String toName = documentData.contactName;
    String toEmail = null;/*from w  ww  . ja  va2  s.  c  o m*/
    final String replyToName = documentData.salesrepName;
    String replyToEmail = null;

    boolean moreThanOneCustomer = checks.get("moreThanOneCustomer").booleanValue();
    boolean moreThanOnesalesRep = checks.get("moreThanOnesalesRep").booleanValue();
    if (moreThanOneCustomer) {
        toEmail = documentData.contactEmail;
    } else {
        toEmail = vars.getStringParameter("toEmail");
    }

    if (moreThanOnesalesRep) {
        replyToEmail = documentData.salesrepEmail;
    } else {
        replyToEmail = vars.getStringParameter("replyToEmail");
    }
    if (differentDocTypes.size() > 1) {
        try {
            EmailDefinition emailDefinition = report.getDefaultEmailDefinition();
            emailSubject = emailDefinition.getSubject();
            emailBody = emailDefinition.getBody();
        } catch (ReportingException e) {
            log4j.error(e.getMessage(), e);
        }
    } else {
        emailSubject = vars.getStringParameter("emailSubject");
        emailBody = vars.getStringParameter("emailBody");
    }

    // TODO: Move this to the beginning of the print handling and do nothing
    // if these conditions fail!!!)

    if ((replyToEmail == null || replyToEmail.length() == 0)) {
        throw new ServletException(Utility.messageBD(this, "NoSalesRepEmail", vars.getLanguage()));
    }

    if ((toEmail == null || toEmail.length() == 0)) {
        throw new ServletException(Utility.messageBD(this, "NoCustomerEmail", vars.getLanguage()));
    }

    // Replace special tags

    emailSubject = emailSubject.replaceAll("@cus_ref@", Matcher.quoteReplacement(cusReference));
    emailSubject = emailSubject.replaceAll("@our_ref@", Matcher.quoteReplacement(ourReference));
    emailSubject = emailSubject.replaceAll("@cus_nam@", Matcher.quoteReplacement(toName));
    emailSubject = emailSubject.replaceAll("@sal_nam@", Matcher.quoteReplacement(replyToName));
    emailSubject = emailSubject.replaceAll("@bp_nam@", Matcher.quoteReplacement(report.getBPName()));
    emailSubject = emailSubject.replaceAll("@doc_date@", Matcher.quoteReplacement(report.getDocDate()));
    emailSubject = emailSubject.replaceAll("@doc_nextduedate@",
            Matcher.quoteReplacement(report.getMinDueDate()));
    emailSubject = emailSubject.replaceAll("@doc_lastduedate@",
            Matcher.quoteReplacement(report.getMaxDueDate()));
    emailSubject = emailSubject.replaceAll("@doc_desc@", Matcher.quoteReplacement(report.getDocDescription()));

    emailBody = emailBody.replaceAll("@cus_ref@", Matcher.quoteReplacement(cusReference));
    emailBody = emailBody.replaceAll("@our_ref@", Matcher.quoteReplacement(ourReference));
    emailBody = emailBody.replaceAll("@cus_nam@", Matcher.quoteReplacement(toName));
    emailBody = emailBody.replaceAll("@sal_nam@", Matcher.quoteReplacement(replyToName));
    emailBody = emailBody.replaceAll("@bp_nam@", Matcher.quoteReplacement(report.getBPName()));
    emailBody = emailBody.replaceAll("@doc_date@", Matcher.quoteReplacement(report.getDocDate()));
    emailBody = emailBody.replaceAll("@doc_nextduedate@", Matcher.quoteReplacement(report.getMinDueDate()));
    emailBody = emailBody.replaceAll("@doc_lastduedate@", Matcher.quoteReplacement(report.getMaxDueDate()));
    emailBody = emailBody.replaceAll("@doc_desc@", Matcher.quoteReplacement(report.getDocDescription()));

    String host = null;
    boolean auth = true;
    String username = null;
    String password = null;
    String connSecurity = null;
    int port = 25;

    OBContext.setAdminMode(true);
    try {
        final EmailServerConfiguration mailConfig = OBDal.getInstance().get(EmailServerConfiguration.class,
                vars.getStringParameter("fromEmailId"));

        host = mailConfig.getSmtpServer();

        if (!mailConfig.isSMTPAuthentification()) {
            auth = false;
        }
        username = mailConfig.getSmtpServerAccount();
        password = FormatUtilities.encryptDecrypt(mailConfig.getSmtpServerPassword(), false);
        connSecurity = mailConfig.getSmtpConnectionSecurity();
        port = mailConfig.getSmtpPort().intValue();
    } finally {
        OBContext.restorePreviousMode();
    }

    final String recipientTO = toEmail;
    final String recipientCC = vars.getStringParameter("ccEmail");
    final String recipientBCC = vars.getStringParameter("bccEmail");
    final String replyTo = replyToEmail;
    final String contentType = "text/plain; charset=utf-8";

    if (log4j.isDebugEnabled()) {
        log4j.debug("From: " + senderAddress);
        log4j.debug("Recipient TO (contact email): " + recipientTO);
        log4j.debug("Recipient CC: " + recipientCC);
        log4j.debug("Recipient BCC (user email): " + recipientBCC);
        log4j.debug("Reply-to (sales rep email): " + replyTo);
    }

    List<File> attachments = new ArrayList<File>();
    attachments.add(new File(attachmentFileLocation));

    if (object != null) {
        final Vector<Object> vector = object;
        for (int i = 0; i < vector.size(); i++) {
            final AttachContent objContent = (AttachContent) vector.get(i);
            final File file = prepareFile(objContent, ourReference);
            attachments.add(file);
        }
    }

    try {
        EmailManager.sendEmail(host, auth, username, password, connSecurity, port, senderAddress, recipientTO,
                recipientCC, recipientBCC, replyTo, emailSubject, emailBody, contentType, attachments,
                new Date(), null);
    } catch (Exception exception) {
        log4j.error(exception);
        final String exceptionClass = exception.getClass().toString().replace("class ", "");
        String exceptionString = "Problems while sending the email" + exception;
        exceptionString = exceptionString.replace(exceptionClass, "");
        throw new ServletException(exceptionString);
    } finally {
        // Delete the temporary files generated for the email attachments
        for (File attachment : attachments) {
            if (attachment.exists() && !attachment.isDirectory()) {
                attachment.delete();
            }
        }
    }

    // Store the email in the database
    Connection conn = null;
    try {
        conn = this.getTransactionConnection();

        // First store the email message
        final String newEmailId = SequenceIdData.getUUID();
        if (log4j.isDebugEnabled())
            log4j.debug("New email id: " + newEmailId);

        EmailData.insertEmail(conn, this, newEmailId, vars.getClient(), report.getOrgId(), vars.getUser(),
                EmailType.OUTGOING.getStringValue(), replyTo, recipientTO, recipientCC, recipientBCC,
                Utility.formatDate(new Date(), "yyyyMMddHHmmss"), emailSubject, emailBody,
                report.getBPartnerId(), ToolsData.getTableId(this, report.getDocumentType().getTableName()),
                documentData.documentId);

        releaseCommitConnection(conn);
    } catch (final NoConnectionAvailableException exception) {
        log4j.error(exception);
        throw new ServletException(exception);
    } catch (final SQLException exception) {
        log4j.error(exception);
        try {
            releaseRollbackConnection(conn);
        } catch (final Exception ignored) {
        }

        throw new ServletException(exception);
    }

}

From source file:org.finra.dm.service.helper.Hive13DdlGenerator.java

/**
 * Gets a pattern to match Hive partition sub-directories.
 *
 * @param partitionColumns the list of partition columns
 *
 * @return the newly created pattern to match Hive partition sub-directories.
 *//*from w  w  w  . ja  v a2 s  . c  om*/
public Pattern getHivePathPattern(List<SchemaColumn> partitionColumns) {
    StringBuilder sb = new StringBuilder(26);

    // For each partition column, add a regular expression to match "<COLUMN_NAME|COLUMN-NAME>=<VALUE>" sub-directory.
    for (SchemaColumn partitionColumn : partitionColumns) {
        String partitionColumnName = partitionColumn.getName();
        // We are using a non-capturing group for the partition column names here - this is done by adding "?:" to the beginning of a capture group.
        sb.append("\\/(?:");
        sb.append(Matcher.quoteReplacement(partitionColumnName));
        // Please note that for subpartition folder, we do support partition column names having all underscores replaced with hyphens.
        sb.append('|');
        sb.append(Matcher.quoteReplacement(partitionColumnName.replace("_", "-")));
        sb.append(")=([^/]+)");
    }

    // Add a regular expression for a trailing "/" and an optional file name.
    sb.append("\\/[^/]*");

    // We do a case-insensitive match for partition column names.
    return Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);
}

From source file:org.openddr.simpleapi.oddr.ODDRService.java

public PropertyValues getPropertyValues(Evidence evdnc) {
    Device deviceFound = null;/*from   w ww . j  a va 2  s  .co m*/
    Browser browserFound = null;
    OperatingSystem osFound = null;
    boolean deviceIdentified = false;
    boolean browserIdentified = false;
    boolean osIdentified = false;
    UserAgent deviceUA = null;
    UserAgent browserUA = null;

    JexlEngine jexl = new JexlEngine();
    ODDRPropertyValues ret = new ODDRPropertyValues();
    Map<String, Vocabulary> vocabularies = vocabularyHolder.getVocabularies();
    Set<String> vocabularyKeys = vocabularies.keySet();

    for (String vocabularyKey : vocabularyKeys) {
        Vocabulary vocabulary = vocabularies.get(vocabularyKey);
        Map<String, VocabularyProperty> properties = vocabulary.getProperties();
        Set<String> propertyKeys = properties.keySet();
        for (String propertyKey : propertyKeys) {
            PropertyName propertyName = new ODDRPropertyName(propertyKey, vocabularyKey);
            for (int i = 0; i < properties.get(propertyKey).getAspects().length; i++) {
                PropertyRef propertyRef = new ODDRPropertyRef(propertyName,
                        properties.get(propertyKey).getAspects()[i]);
                if (ASPECT_DEVICE.equals(propertyRef.getAspectName())) {
                    if (!deviceIdentified) {
                        if (deviceUA == null) {
                            deviceUA = UserAgentFactory.newDeviceUserAgent(evdnc);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            deviceFound = ((BufferedODDRHTTPEvidence) evdnc).getDeviceFound();
                        }
                        if (deviceFound == null) {
                            deviceFound = deviceIdentificator.get(deviceUA, this.threshold);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            ((BufferedODDRHTTPEvidence) evdnc).setDeviceFound(deviceFound);
                        }
                        deviceIdentified = true;
                    }
                    String property = null;
                    if (deviceFound != null) {
                        property = deviceFound.get(propertyRef.getLocalPropertyName());
                        ret.addProperty(new ODDRPropertyValue(property, properties.get(propertyKey).getType(),
                                propertyRef));

                    } else {
                        ret.addProperty(new ODDRPropertyValue(null, properties.get(propertyKey).getType(),
                                propertyRef));
                    }
                    continue;

                } else if (ASPECT_WEB_BROWSER.equals(propertyRef.getAspectName())) {
                    if (!browserIdentified) {
                        if (browserUA == null) {
                            browserUA = UserAgentFactory.newBrowserUserAgent(evdnc);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            browserFound = ((BufferedODDRHTTPEvidence) evdnc).getBrowserFound();
                        }
                        if (browserFound == null) {
                            browserFound = browserIdentificator.get(browserUA, this.threshold);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            ((BufferedODDRHTTPEvidence) evdnc).setBrowserFound(browserFound);
                        }

                        browserIdentified = true;
                    }
                    String property = null;
                    if (browserFound != null) {
                        property = browserFound.get(propertyRef.getLocalPropertyName());
                        ret.addProperty(new ODDRPropertyValue(property, properties.get(propertyKey).getType(),
                                propertyRef));

                    } else {
                        ret.addProperty(new ODDRPropertyValue(null, properties.get(propertyKey).getType(),
                                propertyRef));
                    }
                    continue;

                } else if (ASPECT_OPERATIVE_SYSTEM.equals(propertyRef.getAspectName())) {
                    if (!osIdentified) {
                        if (deviceUA == null) {
                            deviceUA = UserAgentFactory.newDeviceUserAgent(evdnc);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            osFound = ((BufferedODDRHTTPEvidence) evdnc).getOsFound();
                        }
                        if (osFound == null) {
                            osFound = osIdentificator.get(deviceUA, this.threshold);
                        }
                        if (evdnc instanceof BufferedODDRHTTPEvidence) {
                            ((BufferedODDRHTTPEvidence) evdnc).setOsFound(osFound);
                        }

                        osIdentified = true;
                    }
                    String property = null;
                    if (osFound != null) {
                        property = osFound.get(propertyRef.getLocalPropertyName());
                        ret.addProperty(new ODDRPropertyValue(property, properties.get(propertyKey).getType(),
                                propertyRef));

                    } else {
                        ret.addProperty(new ODDRPropertyValue(null, properties.get(propertyKey).getType(),
                                propertyRef));
                    }
                    continue;

                } else if (ASPECT_GROUP.equals(propertyRef.getAspectName())) {
                    try {
                        String jexlExp = properties.get(propertyKey).getExpr();
                        Matcher m = groupRegexprPattern.matcher(jexlExp);
                        while (m.find()) {
                            String id = m.group(1);
                            String propertyValueString = null;
                            PropertyValue propertyValue = getPropertyValue(evdnc,
                                    vocabulary.getVocabularyVariables().get(id).getName(),
                                    vocabulary.getVocabularyVariables().get(id).getAspect(),
                                    vocabulary.getVocabularyVariables().get(id).getVocabulary());
                            propertyValueString = (propertyValue.exists() ? propertyValue.getString() : "-");
                            String toReplace = "$" + id;
                            jexlExp = jexlExp.replaceAll(Matcher.quoteReplacement(toReplace),
                                    "'" + propertyValueString + "'");
                        }
                        Expression e = jexl.createExpression(jexlExp);
                        JexlContext jc = new MapContext();
                        Object o = e.evaluate(jc);
                        ret.addProperty(new ODDRPropertyValue(o.toString(),
                                properties.get(propertyKey).getType(), propertyRef));

                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }

    return ret;
}