Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

In this page you can find the example usage for java.lang StringBuilder indexOf.

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:tools.xor.AbstractBO.java

@Override
public void set(String propertyPath, Map<String, Object> propertyResult, EntityType domainEntityType)
        throws Exception {

    if (domainEntityType.isOpen()) {
        String propertyName = propertyPath.substring(propertyPath.indexOf(OpenType.DELIM) + 1);
        Property property = getType().getProperty(propertyName);
        ((ExtendedProperty) property).setValue(this,
                propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)));
        return;//  w  w w  .  j  a v  a  2  s. c  o m
    }

    // If we are setting a null value then nothing needs to be done
    if (propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)) == null)
        return;

    // Since this builds the path for objects already persisted, the identifier value will not be null
    String[] pathSteps = propertyPath.split(Settings.PATH_DELIMITER_REGEX);
    BusinessObject current = this;
    StringBuilder currentPath = new StringBuilder(QueryViewProperty.ROOT_PROPERTY_NAME);
    for (String step : pathSteps) {
        if (currentPath.length() > 0)
            currentPath.append(Settings.PATH_DELIMITER);
        currentPath.append(step);

        Property property = current.getInstanceProperty(step);
        Property domainProperty = domainEntityType
                .getProperty(currentPath.substring(currentPath.indexOf(Settings.PATH_DELIMITER) + 1));
        if (property == null)
            throw new RuntimeException("Unable to resolve property: " + propertyPath);

        //Object propertyDO = current.get(property);
        Object propertyDO = current.getDataObject(property);
        if (!property.isMany()) {
            if (property.getType().isDataType()) {
                // Populate the field and return the data object
                ((ExtendedProperty) property).setValue(current,
                        propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)));
                return;
            }

            if (((EntityType) property.getType()).isEmbedded()) {
                // Is this true? 
                // TODO: Check if the embedded object gets created
                // What about collection of embedded objects?
                // Maybe we only allow the fast path of object creation, i.e., the result needs to be sorted
                //   and we use this ability to construct the fields as we scan through each row.
                //   This also allows optimization using OpenCL
                continue; // Embedded objects are automatically created as part of its lifecycle owner
            }

            if (propertyDO == null) {
                // Set the natural key if there is one
                Map<String, Object> naturalKeyValues = new HashMap<String, Object>();
                if (((EntityType) property.getType()).getNaturalKey() != null) {
                    Set<String> naturalKey = ((EntityType) property.getType()).getNaturalKey();
                    if (naturalKey != null) {
                        for (String key : naturalKey) {
                            Object keyValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER + key);
                            naturalKeyValues.put(key, keyValue);
                        }
                        propertyDO = getByNaturalKey(naturalKeyValues, domainProperty.getType());
                    }
                }
                // Check if there is a data object with the given key
                // Get the identifier value
                Object idValue = null;
                if (propertyDO == null && ((EntityType) property.getType()).getIdentifierProperty() != null) {
                    idValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER
                            + ((EntityType) property.getType()).getIdentifierProperty().getName());
                    propertyDO = getBySurrogateKey(idValue, domainProperty.getType());
                }

                if (propertyDO == null) { // create and set the instance object
                    // check if we are narrowing
                    String narrowToType = (String) propertyResult.get(
                            currentPath + Settings.PATH_DELIMITER + QueryViewProperty.ENTITYNAME_ATTRIBUTE);
                    EntityType objectType = (EntityType) property.getType();
                    if (narrowToType != null)
                        objectType = (EntityType) getObjectCreator().getDAS().getType(narrowToType);
                    propertyDO = current.createDataObject(idValue, naturalKeyValues, objectType, property);
                }
            }
            if (property.isContainment()) {
                ((BusinessObject) propertyDO).setContainer(current);
                ((BusinessObject) propertyDO).setContainmentProperty(property);
            }

            // Set the instance value in the container
            ((ExtendedProperty) property).setValue(current, ((BusinessObject) propertyDO).getInstance());

            current = (BusinessObject) propertyDO;
        } else {

            //System.out.println("propertyDO class: " + propertyDO.getClass() + ", property: " + property.getName());
            if (propertyDO == null) { // create and set the collection/map object
                propertyDO = current.createDataObject(null, property.getType(), property);
            } else if (!BusinessObject.class.isAssignableFrom(propertyDO.getClass())) {
                propertyDO = objectCreator.createDataObject(propertyDO, property.getType(), current, property);
            }
            current = (BusinessObject) propertyDO;
            Object elementDO = null;

            // Get the identifier value from the collection element
            Type elementType = ((ExtendedProperty) property).getElementType();
            Type domainElementType = ((ExtendedProperty) domainProperty).getElementType();

            // Get by the natural key if there is one
            Map<String, Object> naturalKeyValues = new HashMap<String, Object>();
            if (((EntityType) elementType).getNaturalKey() != null) {
                Set<String> naturalKey = ((EntityType) elementType).getNaturalKey();
                for (String key : naturalKey) {
                    Object keyValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER + key);
                    naturalKeyValues.put(key, keyValue);
                }

                // Get the element
                elementDO = getByNaturalKey(naturalKeyValues, domainElementType);
            }

            Object idValue = null;
            if (elementDO == null && ((EntityType) elementType).getIdentifierProperty() != null) {
                idValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER
                        + ((EntityType) elementType).getIdentifierProperty().getName());
                elementDO = getBySurrogateKey(idValue, domainElementType);
            }

            // check flag to see if the containment should be set
            if (elementDO != null && property.isContainment()) {
                ((BusinessObject) elementDO).setContainer(current); // Containment property is null for a collection element
            }

            if (elementDO == null) { // create and set the instance object

                // Get the property instance if possible
                Object elementInstance = null;

                if (((ExtendedProperty) property).isMap()) {
                    Object keyValue = propertyResult
                            .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.MAP_KEY_ATTRIBUTE);
                    Map map = (Map) current.getInstance();
                    elementInstance = map.get(keyValue);
                }

                if (elementInstance == null) {
                    if (idValue != null || naturalKeyValues.size() > 0)
                        elementDO = current.createDataObject(idValue, naturalKeyValues,
                                (EntityType) elementType, null);
                    else
                        return; // Does not have a collection element
                } else
                    // create the data object using the instance
                    elementDO = objectCreator.createDataObject(elementInstance, elementType, current, null);

                // check flag to see if the containment should be set
                if (property.isContainment())
                    ((BusinessObject) elementDO).setContainer(current); // Containment property is null for a collection element
            }

            // Add the element
            Object elementInstance = ((BusinessObject) elementDO).getInstance();
            if (((ExtendedProperty) property).isMap()) {
                // If this is a map, get the key
                Object keyValue = propertyResult
                        .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.MAP_KEY_ATTRIBUTE);
                Map map = (Map) current.getInstance();
                map.put(keyValue, elementInstance);
            } else if (((ExtendedProperty) property).isList()) {
                Object indexValue = propertyResult
                        .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.LIST_INDEX_ATTRIBUTE);
                List list = (List) current.getInstance();
                int index = Integer.parseInt(indexValue.toString());
                if (index >= list.size() || list.get(index) != elementInstance)
                    list.add(elementInstance);
            } else if (((ExtendedProperty) property).isSet()) {
                // Currently Immutable JSON is treated as a set, so we should check for this
                if (current.getInstance() instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) current.getInstance();
                    jsonArray.put(elementInstance);
                } else {
                    Set set = (Set) current.getInstance();
                    set.add(elementInstance);
                }
            }

            current = (BusinessObject) elementDO;
        }
    }

    return;
}

From source file:net.sourceforge.fenixedu.domain.Degree.java

public String getFilteredName(final ExecutionYear executionYear, final Locale locale) {
    final StringBuilder res = new StringBuilder(getNameFor(executionYear).getContent(locale));

    for (final Space campus : Space.getAllCampus()) {
        String toRemove = " - " + campus.getName();
        if (res.toString().contains(toRemove)) {
            res.replace(res.indexOf(toRemove), res.indexOf(toRemove) + toRemove.length(), StringUtils.EMPTY);
        }//from w ww  . j ava  2 s. c  o  m
    }

    return res.toString();
}

From source file:com.longevitysoft.java.bigslice.server.SlicerSlic3r.java

@Override
public void slice(@Header(value = Constants.MSG_HEADER_SLICE_CONFIG_ARRAY_LIST) String configList,
        @Header(value = Constants.MSG_HEADER_CAMEL_FILE_ABSOLUTE_PATH) String filePath,
        @Header(value = Constants.MSG_HEADER_OUTPUT_PATH) String headerOutputFilename) {
    Endpoint epSlice = camel.getEndpoint(Constants.EP_NAME_JMS_QUEUE_PENDINGSTL);
    Exchange inEx = epSlice.createExchange(ExchangePattern.InOnly);
    // check if output filename header present
    StringBuilder configFileParam = new StringBuilder();
    if (null != configList) {
        configList = configList.trim();//from   w  ww. j a  v  a2s  .  co m
        String[] configs = configList.split(",");
        LOG.debug("configs received in msg header");
        configFileParam.append(Constants.SPACE);
        for (String configName : configs) {
            configFileParam.append(Constants.SLIC3R_PARAM_NAME_LOAD).append(Constants.SPACE).append(configName);
        }
    }
    // check if output filename header present
    try {
        StringBuilder gcodeOutputFilename = new StringBuilder().append(Constants.PARENT_DIR)
                .append(Constants.FILEPATH_GCODEOUT); // slic3r
        // uses
        // STL
        // folder
        // by
        // default
        if (null != headerOutputFilename) {
            gcodeOutputFilename.append(Constants.SLASH)
                    .append(headerOutputFilename.replace(Constants.TILDE_BANG_TILDE,
                            Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE + Constants.UNDERSCORE));
            // init directory-tree in output filename
            int lastSlash = headerOutputFilename.lastIndexOf("/");
            if (0 < lastSlash) {
                String outputTree = headerOutputFilename.substring(0, lastSlash);
                outputTree = outputTree.replace("/./", "/");
                File outDir = new File(buildOutputPath() + Constants.SLASH + outputTree);
                outDir.mkdirs();
            }
        } else {
            gcodeOutputFilename.append(Constants.SLASH).append(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM__HH-mm-ss");
            gcodeOutputFilename.append("_TS").append(sdf.format(Calendar.getInstance().getTime()));
        }
        if (null == pathToExecutable) {
            throw new InterruptedException("no exec path found");
        }
        for (int i = 0; i < pathToExecutable.size(); i++) {
            String execPath = pathToExecutable.get(i);
            // inject executable name into gcode output filename
            String insToken = null;
            int insertPos = gcodeOutputFilename.indexOf(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            if (0 < insertPos) {
                insertPos += Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE.length();
                if (null != execOutputFilenameFilter) {
                    insToken = execOutputFilenameFilter.get(i);
                }
                if (null == insToken) {
                    insToken = sanitizeFilename(execPath);
                }
                insToken = Constants.UNDERSCORE + insToken;
            }
            // build exec string
            final StringBuilder execStr = new StringBuilder(execPath).append(configFileParam)
                    .append(Constants.SPACE).append(Constants.SLIC3R_CLI_PARAM_OUTPUT_FILENAME_FORMAT)
                    .append(gcodeOutputFilename.substring(0, insertPos)).append(insToken)
                    .append(gcodeOutputFilename.substring(insertPos, gcodeOutputFilename.length()))
                    .append(Constants.EXT_GCODE).append(Constants.SPACE).append(filePath);
            LOG.debug("executing-slic3r: " + execStr + Constants.NEWLINE);
            final String fPath = filePath;
            final StringBuilder gcodeOutFName = gcodeOutputFilename;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Runtime rt = Runtime.getRuntime();
                        RuntimeExec rte = new RuntimeExec();
                        StreamWrapper error, output;
                        Process proc = rt.exec(execStr.toString());
                        error = rte.getStreamWrapper(proc.getErrorStream(), Constants.STREAM_NAME_ERROR);
                        output = rte.getStreamWrapper(proc.getInputStream(), Constants.STREAM_NAME_OUTPUT);
                        int exitVal = 0;
                        error.start();
                        output.start();
                        error.join(3000);
                        output.join(3000);
                        exitVal = proc.waitFor();
                        // TODO process exitVal for caller - decide what to
                        // do in
                        // http://camel.apache.org/exception-clause.html
                        LOG.info(new StringBuilder().append("stl-file-path: ").append(fPath)
                                .append(", output-file-path:").append(gcodeOutFName).append(Constants.NEWLINE)
                                .append(", proc-output: ").append(output.getMessage()).append(Constants.NEWLINE)
                                .append(", proc-error: ").append(error.getMessage()).toString());
                    } catch (Exception e) {
                        LOG.trace(e.toString());
                    }
                }
            });
        }
    } catch (InterruptedException e) {
        LOG.trace(e.toString());
    }
}

From source file:org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery.java

private String generateParsingError(ParsingResult<ASTNode> result) {
    StringBuilder parsingErrorBuilder = new StringBuilder(
            "Parsing error" + ((result.parseErrors.size() > 1) ? "s" : "") + ": \n");
    InputBuffer inputBuffer = result.inputBuffer;
    String parsedLine = inputBuffer.extract(0, Integer.MAX_VALUE);

    StringBuilder invalidInputLineBuilder = null;
    for (ParseError parseError : result.parseErrors) {
        StringBuilder otherErrorLineBuilder = getCaratLineStringBuilder(parsedLine);

        // NOTE for some reason, these indexes start at 1, not 0
        int originalEndIndex = inputBuffer.getOriginalIndex(parseError.getEndIndex()) - 1;
        int originalStartIndex = inputBuffer.getOriginalIndex(parseError.getStartIndex()) - 1;

        if (parseError.getClass().isAssignableFrom(InvalidInputError.class)) {
            // Combine all InvalidInputError's
            if (invalidInputLineBuilder == null) {
                invalidInputLineBuilder = getCaratLineStringBuilder(parsedLine);
            }/*from w  w  w.  ja v  a2  s  . c o  m*/

            addCaretsToStringBuilder(invalidInputLineBuilder, originalEndIndex, originalStartIndex);
        } else {
            // output other types of errors separately
            parsingErrorBuilder.append("\nError found in: \n");

            addCaretsToStringBuilder(otherErrorLineBuilder, originalEndIndex, originalStartIndex);

            parsingErrorBuilder.append("\n\t");
            parsingErrorBuilder.append(parsedLine);
            parsingErrorBuilder.append("\n\t");
            parsingErrorBuilder.append(otherErrorLineBuilder);
        }
    }

    if (invalidInputLineBuilder != null) {
        // if the first and last occurrence of CARET aren't the same, there are more than one in
        // the string
        parsingErrorBuilder.append("\nInvalid character")
                .append((invalidInputLineBuilder.indexOf(CARET) != invalidInputLineBuilder.lastIndexOf(CARET))
                        ? "s"
                        : "")
                .append(" found in: \n");
        parsingErrorBuilder.append("\n\t");
        parsingErrorBuilder.append(parsedLine);
        parsingErrorBuilder.append("\n\t");
        parsingErrorBuilder.append(invalidInputLineBuilder);
    }
    return parsingErrorBuilder.toString();
}

From source file:pltag.corpus.StringTree.java

/**
 * Prints the structure of a string tree in bracketed notation
 *
 * @param nodeID//from w w w .ja  va2  s .  c o m
 * @param printSemantics
 * @return
 */
public String getStructure(int nodeID, boolean printSemantics) {
    StringBuilder struct = new StringBuilder();
    ArrayList<Integer> childlist = children.get(nodeID);
    if (childlist == null || childlist.isEmpty()) {
        return getLexName(nodeID, printSemantics);
        //return nodeID + ":" +getLexName(nodeID);
    }
    StringBuilder childString = new StringBuilder();
    for (Integer childid : childlist) {
        //System.err.print(nodeID + ":" + childString + " " + childid + "\n");
        childString.append(" ").append(getStructure(childid, printSemantics));
    }
    String structString;
    if (!fullcategories[nodeID].equals(""))
    //        if (!fullcategories[Integer.parseInt(nodeID)].equals(""))
    {
        struct.append("( ").append(getLexName(nodeID, printSemantics)).append(childString.toString())
                .append(")");
        structString = struct.toString();
    } else {
        int upind = childString.indexOf("^");
        int downind = childString.indexOf("_");
        structString = childString.subSequence(0, upind + 1) + "null" + childString.substring(downind);
        structString = structString.trim();
    }
    //struct = "( "+nodeID + ":" + getLexName(nodeID)+childString+")";
    return structString;
}

From source file:org.saiku.plugin.SaikuContentGenerator.java

@Override
public void createContent(OutputStream out) throws Exception {
    try {//from  ww  w .  j a  va 2  s  .c  o m
        StringBuilder html = new StringBuilder();
        final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class,
                PentahoSessionHolder.getSession());
        final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager
                .getClassLoader(PluginConfig.PLUGIN_NAME);
        File pluginDir = pluginClassloader.getPluginDir();

        IParameterProvider requestParams = parameterProviders.get(IParameterProvider.SCOPE_REQUEST);
        if (requestParams == null) {
            LOG.error("Parameter provider is null");
            throw new NullPointerException("Parameter provider is null");
        }
        String run = requestParams.getStringParameter("run", ""); //$NON-NLS-1$

        File indexFile;
        String extrasnippet = "";
        if (run != null && run.equals("table")) {
            indexFile = new File(pluginDir, "ui/run.html");
        } else if (run != null && run.equals("view")) {
            indexFile = new File(pluginDir, "ui/index.html");
            extrasnippet += "PLUGIN_REMOVE_CONTENT = 'a[href=\"#save_query\"], a[href=\"#automatic_execution\"], a[href=\"#toggle_fields\"], a[href=\"#switch_to_mdx\"], a[href=\"#run_query\"]';\r\n";
            extrasnippet += "ALLOW_PUC_SAVE = false;\r\n";
            extrasnippet += "REDUCED = true;\r\n";

        } else {
            indexFile = new File(pluginDir, "ui/index.html");
            extrasnippet += "PLUGIN_REMOVE_CONTENT = 'a[href=\"#save_query\"]';\r\n";

        }

        FileReader fr = new FileReader(indexFile);
        BufferedReader br = new BufferedReader(fr);
        String inputLine;

        while ((inputLine = br.readLine()) != null) {
            html.append(inputLine);
        }
        int bodyend = html.indexOf("</body>");
        if (bodyend >= 0) {
            html.append("\r\n");
            String snippet = "";
            snippet = "<script type=\"text/javascript\">\r\n";

            if (document != null) {
                document = document.replaceAll("\n", " ").replaceAll("\r", " ").replaceAll("  ", " ");
                ;
                snippet += "QUERY = '" + document + "';\r\n";
            }
            snippet += extrasnippet;
            snippet += "</script>\r\n";
            html.insert(bodyend, snippet);
        }

        out.write(html.toString().getBytes(LocaleHelper.getSystemEncoding()));

    } catch (Exception e) {
        throw new Exception("Error creating content", e);
    }

}

From source file:davmail.imap.ImapConnection.java

private void handleFetch(ExchangeSession.Message message, int currentIndex, String parameters)
        throws IOException, MessagingException {
    StringBuilder buffer = new StringBuilder();
    buffer.append("* ").append(currentIndex).append(" FETCH (UID ").append(message.getImapUid());
    if (parameters != null) {
        StringTokenizer paramTokens = new StringTokenizer(parameters);
        while (paramTokens.hasMoreTokens()) {
            @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" })
            String param = paramTokens.nextToken().toUpperCase();
            if ("FLAGS".equals(param)) {
                buffer.append(" FLAGS (").append(message.getImapFlags()).append(')');
            } else if ("RFC822.SIZE".equals(param)) {
                int size;
                if (parameters.indexOf("BODY.PEEK[HEADER.FIELDS (") >= 0) {
                    // Header request, send approximate size
                    size = message.size;
                } else {
                    size = message.getMimeMessageSize();
                }//from  w w  w . ja  va  2s  . com
                buffer.append(" RFC822.SIZE ").append(size);
            } else if ("ENVELOPE".equals(param)) {
                appendEnvelope(buffer, message);
            } else if ("BODYSTRUCTURE".equals(param)) {
                appendBodyStructure(buffer, message);
            } else if ("INTERNALDATE".equals(param) && message.date != null && message.date.length() > 0) {
                try {
                    SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    dateParser.setTimeZone(ExchangeSession.GMT_TIMEZONE);
                    Date date = ExchangeSession.getZuluDateFormat().parse(message.date);
                    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z",
                            Locale.ENGLISH);
                    buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"');
                } catch (ParseException e) {
                    throw new DavMailException("EXCEPTION_INVALID_DATE", message.date);
                }
            } else if (param.equals("RFC822") || param.startsWith("BODY[") || param.startsWith("BODY.PEEK[")
                    || "RFC822.HEADER".equals(param)) {
                // get full param
                if (param.indexOf('[') >= 0) {
                    StringBuilder paramBuffer = new StringBuilder(param);
                    while (paramTokens.hasMoreTokens() && paramBuffer.indexOf("]") < 0) {
                        paramBuffer.append(' ').append(paramTokens.nextToken());
                    }
                    param = paramBuffer.toString();
                }
                // parse buffer size
                int startIndex = 0;
                int maxSize = Integer.MAX_VALUE;
                int ltIndex = param.indexOf('<');
                if (ltIndex >= 0) {
                    int dotIndex = param.indexOf('.', ltIndex);
                    if (dotIndex >= 0) {
                        startIndex = Integer.parseInt(param.substring(ltIndex + 1, dotIndex));
                        maxSize = Integer.parseInt(param.substring(dotIndex + 1, param.indexOf('>')));
                    }
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream partInputStream = null;
                OutputStream partOutputStream = null;

                // try to parse message part index
                String partIndexString = StringUtil.getToken(param, "[", "]");
                if ("".equals(partIndexString) || partIndexString == null) {
                    // write message with headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    partInputStream = message.getRawInputStream();
                } else if ("TEXT".equals(partIndexString)) {
                    // write message without headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    partInputStream = message.getMimeMessage().getRawInputStream();
                } else if ("RFC822.HEADER".equals(param) || partIndexString.startsWith("HEADER")) {
                    // Header requested fetch  headers
                    String[] requestedHeaders = getRequestedHeaders(partIndexString);
                    if (requestedHeaders != null) {
                        // OSX Lion special flags request
                        if (requestedHeaders.length == 1 && "content-class".equals(requestedHeaders[0])
                                && message.contentClass != null) {
                            baos.write("Content-class: ".getBytes("UTF-8"));
                            baos.write(message.contentClass.getBytes("UTF-8"));
                            baos.write(13);
                            baos.write(10);
                        } else {
                            Enumeration headerEnumeration = message.getMatchingHeaderLines(requestedHeaders);
                            while (headerEnumeration.hasMoreElements()) {
                                baos.write(((String) headerEnumeration.nextElement()).getBytes("UTF-8"));
                                baos.write(13);
                                baos.write(10);
                            }
                        }
                    } else {
                        // write headers only
                        partOutputStream = new PartOutputStream(baos, true, false, startIndex, maxSize);
                        partInputStream = message.getRawInputStream();
                    }
                } else {
                    MimePart bodyPart = message.getMimeMessage();
                    String[] partIndexStrings = partIndexString.split("\\.");
                    for (String subPartIndexString : partIndexStrings) {
                        // ignore MIME subpart index, will return full part
                        if ("MIME".equals(subPartIndexString)) {
                            break;
                        }
                        int subPartIndex;
                        // try to parse part index
                        try {
                            subPartIndex = Integer.parseInt(subPartIndexString);
                        } catch (NumberFormatException e) {
                            throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                        }

                        Object mimeBody = bodyPart.getContent();
                        if (mimeBody instanceof MimeMultipart) {
                            MimeMultipart multiPart = (MimeMultipart) mimeBody;
                            if (subPartIndex - 1 < multiPart.getCount()) {
                                bodyPart = (MimePart) multiPart.getBodyPart(subPartIndex - 1);
                            } else {
                                throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                            }
                        } else if (subPartIndex != 1) {
                            throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                        }
                    }

                    // write selected part, without headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    if (bodyPart instanceof MimeMessage) {
                        partInputStream = ((MimeMessage) bodyPart).getRawInputStream();
                    } else {
                        partInputStream = ((MimeBodyPart) bodyPart).getRawInputStream();
                    }
                }

                // copy selected content to baos
                if (partInputStream != null && partOutputStream != null) {
                    IOUtil.write(partInputStream, partOutputStream);
                    partInputStream.close();
                    partOutputStream.close();
                }
                baos.close();

                if ("RFC822.HEADER".equals(param)) {
                    buffer.append(" RFC822.HEADER ");
                } else {
                    buffer.append(" BODY[").append(partIndexString).append(']');
                }
                // partial
                if (startIndex > 0 || maxSize != Integer.MAX_VALUE) {
                    buffer.append('<').append(startIndex).append('>');
                }
                buffer.append(" {").append(baos.size()).append('}');
                sendClient(buffer.toString());
                // log content if less than 2K
                if (LOGGER.isDebugEnabled() && baos.size() < 2048) {
                    LOGGER.debug(new String(baos.toByteArray(), "UTF-8"));
                }
                os.write(baos.toByteArray());
                os.flush();
                buffer.setLength(0);
            }
        }
    }
    buffer.append(')');
    sendClient(buffer.toString());
    // do not keep message content in memory
    message.dropMimeMessage();
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.SyncJob.java

private void doExportPointHandling(ExportEntity entity) {
    StringBuilder confirmation = new StringBuilder();
    StringBuilder notice = new StringBuilder();

    if (!entity.isToBeDeleted()) {
        confirmation.append("Copy of ").append(entity.getVfsPath()).append(" to ")
                .append(entity.getDestination()).append(" - ");
        File file = new File(entity.getSourcePath());
        if (file.exists()) {
            if (file.isFile()) {
                try {
                    FileUtils.copyFile(file, new File(entity.getTargetPath()));
                    confirmation.append("SUCCESS");
                } catch (IOException e) {
                    confirmation.insert(0, ERROR_PREFIX);
                    confirmation.append("FAILED (").append(e.getMessage()).append(")");
                }/*from ww  w .  jav  a2  s. co m*/
            } else if (file.isDirectory()) {
                try {
                    FileUtils.copyDirectory(file, new File(entity.getTargetPath()));
                    confirmation.append("SUCCESS");
                } catch (IOException e) {
                    confirmation.insert(0, ERROR_PREFIX);
                    confirmation.append("FAILED (").append(e.getMessage()).append(")");
                }
            }
        } else {
            confirmation.append(" - FILE NOT FOUND");
        }
    } else {
        String targetPath = entity.getTargetPath();
        String vfsPath = entity.getVfsPath();

        deleteExportedResource(vfsPath, targetPath, confirmation, notice);
    }
    if (confirmation.indexOf(ERROR_PREFIX) > -1) {
        console.error(confirmation.toString());
    } else {
        console.info(confirmation.toString());
    }
    if (notice.length() > 0) {
        console.notice(notice.toString());
    }
}

From source file:org.oscelot.blackboard.lti.Utils.java

public static String getOrg(Id id, boolean isCourse) {

    String org = "";
    StringBuilder orgs = new StringBuilder(",");
    if (B2Context.getIsVersion(9, 1, 8)) {
        NodeAssociationManager nodeAssociationManager = NodeManagerFactory.getAssociationManager();
        NodeManager nodeManager = NodeManagerFactory.getHierarchyManager();
        try {//from   w  w  w .  j  a va 2  s  .  c om
            List<Node> nodes;
            if (B2Context.getIsVersion(9, 1, 10)) {
                ObjectType type;
                if (isCourse) {
                    type = ObjectType.Course;
                } else {
                    type = ObjectType.User;
                }
                nodes = nodeAssociationManager.loadAssociatedNodes(id, type);
            } else if (isCourse) {
                nodes = nodeAssociationManager.loadCourseAssociatedNodes(id);
            } else {
                nodes = nodeAssociationManager.loadUserAssociatedNodes(id);
            }
            Node node;
            Id nodeId;
            for (Iterator<Node> iter = nodes.iterator(); iter.hasNext();) {
                node = iter.next();
                do {
                    if (orgs.indexOf("," + node.getName() + ",") < 0) {
                        orgs.append("dc=").append(node.getName()).append(",");
                    }
                    nodeId = node.getParentId();
                    if (nodeId != null) {
                        node = nodeManager.loadNodeById(nodeId);
                    }
                } while (nodeId != null);
            }
        } catch (PersistenceException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (orgs.length() > 1) {
            org = orgs.substring(1, orgs.length() - 1);
        }
    }

    return org;

}

From source file:com.strider.datadefender.DatabaseAnonymizer.java

/**
 * Creates the SELECT query for key and update columns.
 * /*from   www.  j av a  2  s.c o  m*/
 * @param tableName
 * @param keys
 * @param columns
 * @return 
 */
private PreparedStatement getSelectQueryStatement(final IDBFactory dbFactory, final Table table,
        final Collection<String> keys, final Collection<String> columns) throws SQLException {

    final List<String> params = new LinkedList<>();
    final StringBuilder query = new StringBuilder("SELECT DISTINCT ");
    query.append(StringUtils.join(keys, ", ")).append(", ").append(StringUtils.join(columns, ", "))
            .append(" FROM ").append(table.getName());

    final List<Exclude> exclusions = table.getExclusions();
    if (exclusions != null) {
        String separator = " WHERE (";
        for (final Exclude exc : exclusions) {
            final String eq = exc.getEqualsValue();
            final String lk = exc.getLikeValue();
            final boolean nl = exc.isExcludeNulls();
            final String col = exc.getName();

            if (col != null && col.length() != 0) {
                if (eq != null) {
                    query.append(separator).append('(').append(col).append(" != ? OR ").append(col)
                            .append(" IS NULL)");
                    params.add(eq);
                    separator = AND;
                }
                if (lk != null && lk.length() != 0) {
                    query.append(separator).append('(').append(col).append(" NOT LIKE ? OR ").append(col)
                            .append(" IS NULL)");
                    params.add(lk);
                    separator = AND;
                }
                if (nl) {
                    query.append(separator).append(col).append(" IS NOT NULL");
                    separator = AND;
                }
            }
        }

        if (query.indexOf(" WHERE (") != -1) {
            separator = ") AND (";
        }

        for (final Exclude exc : exclusions) {
            final String neq = exc.getNotEqualsValue();
            final String nlk = exc.getNotLikeValue();
            final String col = exc.getName();

            if (neq != null) {
                query.append(separator).append(col).append(" = ?");
                separator = " OR ";
            }
            if (nlk != null && nlk.length() != 0) {
                query.append(separator).append(col).append(" LIKE ?");
                separator = " OR ";
            }

        }

        if (query.indexOf(" WHERE (") != -1) {
            query.append(')');
        }
    }

    final PreparedStatement stmt = dbFactory.getConnection().prepareStatement(query.toString(),
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    if (dbFactory.getVendorName().equalsIgnoreCase("mysql")) {
        stmt.setFetchSize(Integer.MIN_VALUE);
    }

    int paramIndex = 1;
    for (final String param : params) {
        stmt.setString(paramIndex, param);
        ++paramIndex;
    }

    log.debug("Querying for: " + query.toString());
    if (params.size() > 0) {
        log.debug("\t - with parameters: " + StringUtils.join(params, ','));
    }

    return stmt;
}