Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

In this page you can find the example usage for java.lang StringBuffer setLength.

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:org.codehaus.mojo.sql.SqlExecMojo.java

/**
 * read in lines and execute them//ww w .  j  av a 2s . c o m
 * 
 * @param reader the reader
 * @param out the outputstream
 * @throws SQLException
 * @throws IOException
 */
private void runStatements(Reader reader, PrintStream out) throws SQLException, IOException {
    String line;

    if (enableBlockMode) {
        //no need to parse the content, ship it directly to jdbc in one sql statement
        line = IOUtil.toString(reader);
        execSQL(line, out);
        return;
    }

    StringBuffer sql = new StringBuffer();

    BufferedReader in = new BufferedReader(reader);

    while ((line = in.readLine()) != null) {
        if (!keepFormat) {
            line = line.trim();
        }

        if (!keepFormat) {
            if (line.startsWith("//")) {
                continue;
            }
            if (line.startsWith("--")) {
                continue;
            }
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String token = st.nextToken();
                if ("REM".equalsIgnoreCase(token)) {
                    continue;
                }
            }
        }

        if (!keepFormat) {
            sql.append(" ").append(line);
        } else {
            sql.append("\n").append(line);
        }

        // SQL defines "--" as a comment to EOL
        // and in Oracle it may contain a hint
        // so we cannot just remove it, instead we must end it
        if (!keepFormat) {
            if (SqlSplitter.containsSqlEnd(line, delimiter) == SqlSplitter.NO_END) {
                sql.append("\n");
            }
        }

        if ((delimiterType.equals(DelimiterType.NORMAL) && SqlSplitter.containsSqlEnd(line, delimiter) > 0)
                || (delimiterType.equals(DelimiterType.ROW) && line.trim().equals(delimiter))) {
            execSQL(sql.substring(0, sql.length() - delimiter.length()), out);
            sql.setLength(0); // clean buffer
        }
    }

    // Catch any statements not followed by ;
    if (!sql.toString().equals("")) {
        execSQL(sql.toString(), out);
    }
}

From source file:com.pureinfo.studio.db.txt2SRM.impl.SchoolSCITxtImportRunner.java

/**
 * Converts the properties whose type are different from SRM.
 * /*from  w  w  w.j a  va2 s .  c  o m*/
 * @param _oldObj
 * @param _newObj
 * @throws Exception
 */
private boolean convert(DolphinObject _oldObj, DolphinObject _newObj, List _errorDataList) throws Exception {
    Element convert = m_xmlConfig.element("data");
    List properties = convert.element("convert").elements();
    Element element;
    String sFrom, sTo, sRef, sForeignKey;
    Object value = null;
    boolean bConvertError = false;
    boolean bvalidate = true;
    for (int i = 0; i < properties.size(); i++) {
        bvalidate = true;
        element = (Element) properties.get(i);
        if (element.attributeValue("provider") != null)
            continue;
        sFrom = element.attributeValue("from");
        sTo = element.attributeValue("to");
        sRef = element.attributeValue("ref");

        // to convert property value
        if (!_oldObj.hasProperty(sFrom)) {
            continue;
            // throw new PureException(PureException.PROPERTY_NOTFOUND,
            // sFrom);
        }
        if (isPropertySet(_newObj, sTo))
            continue; // skip

        // else
        try {
            sForeignKey = element.attributeValue("fk");
            String expandCondition = null, expandPropertyDebug = null;
            StringBuffer expandConditionBuffer = new StringBuffer();
            StringBuffer expandPropertyDebugBuffer = new StringBuffer();
            Element expandElement;
            List expands = element.elements("expand");
            if (expands.size() > 0) {
                for (int j = 0; j < expands.size(); j++) {
                    expandElement = (Element) expands.get(i);
                    String expandPropertyValue = _oldObj.getProperty(expandElement.attributeValue("from"))
                            .toString();
                    expandConditionBuffer.append(" " + expandElement.attributeValue("to"));
                    expandConditionBuffer.append('=');
                    expandConditionBuffer.append(expandPropertyValue);
                    expandConditionBuffer.append(" and ");
                    expandPropertyDebugBuffer.append("(" + expandElement.attributeValue("from") + "\""
                            + expandPropertyValue + '\"' + ')');
                }
            }
            if (expandConditionBuffer.length() > 0) {
                expandCondition = expandConditionBuffer.toString();
                expandPropertyDebug = expandPropertyDebugBuffer.toString();
            }
            expandConditionBuffer.setLength(0);
            if (element.attributeValue("validate") != null
                    && element.attributeValue("validate").equals("false"))
                bvalidate = false;
            value = this.lookupRefValue(sRef, _oldObj.getProperty(sFrom), sForeignKey, sFrom, _errorDataList,
                    expandCondition, expandPropertyDebug, bvalidate);

            if (value == null) {
                bConvertError = true;
            } else {
                _newObj.setProperty(sTo, value);
            }

        } catch (Exception ex) {
            throw new PureException(PureException.INVALID_VALUE,
                    "convert " + sFrom + "[" + value + "] to " + sTo, ex);
        }

    }

    return bConvertError;
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

/**
 * processMeta - handle an individual field
 *///from   w  w w.j  ava2  s .c  o m
private void processMeta(DocumentPojo f, metaField m, String text, SourcePojo source,
        UnstructuredAnalysisConfigPojo uap) {

    boolean bAllowDuplicates = false;
    if ((null != m.flags) && m.flags.contains("U")) {
        bAllowDuplicates = true;
    }
    if ((null == m.scriptlang) || m.scriptlang.equalsIgnoreCase("regex")) {

        Pattern metaPattern = createRegex(m.script, m.flags);

        int timesToRun = 1;
        Object[] currField = null;
        if ((null != m.flags) && m.flags.contains("c")) {
            currField = f.getMetadata().get(m.fieldName);
        }
        if (null != currField) { // chained metadata
            timesToRun = currField.length;
            text = (String) currField[0];
        } //TESTED

        Matcher matcher = metaPattern.matcher(text);
        LinkedList<String> Llist = null;

        for (int ii = 0; ii < timesToRun; ++ii) {
            if (ii > 0) { // (else either just text, or in the above "chained metadata" initialization above)
                text = (String) currField[ii];
                matcher = metaPattern.matcher(text);
            } //TESTED

            StringBuffer prefix = new StringBuffer(m.fieldName).append(':');
            int nFieldNameLen = m.fieldName.length() + 1;

            try {
                while (matcher.find()) {
                    if (null == Llist) {
                        Llist = new LinkedList<String>();
                    }
                    if (null == m.groupNum) {
                        m.groupNum = 0;
                    }
                    String toAdd = matcher.group(m.groupNum);
                    if (null != m.replace) {
                        toAdd = metaPattern.matcher(toAdd).replaceFirst(m.replace);
                    }
                    if ((null != m.flags) && m.flags.contains("H")) {
                        toAdd = StringEscapeUtils.unescapeHtml(toAdd);
                    }
                    prefix.setLength(nFieldNameLen);
                    prefix.append(toAdd);
                    String dupCheck = prefix.toString();

                    if (!regexDuplicates.contains(dupCheck)) {
                        Llist.add(toAdd);
                        if (!bAllowDuplicates) {
                            regexDuplicates.add(dupCheck);
                        }
                    }
                }
            } catch (Exception e) {
                this._context.getHarvestStatus().logMessage("processMeta1: " + e.getMessage(), true);
            }
        } //(end metadata chaining handling)
        if (null != Llist) {
            if (null != currField) { // (overwrite)
                f.getMetadata().put(m.fieldName, Llist.toArray());
            } else {
                f.addToMetadata(m.fieldName, Llist.toArray());
            }
        } //TESTED
    } else if (m.scriptlang.equalsIgnoreCase("javascript")) {
        if (null == f.getMetadata()) {
            f.setMetadata(new LinkedHashMap<String, Object[]>());
        }
        //set the script engine up if necessary
        if ((null != source) && (null != uap)) {
            //(these are null if called from new processing pipeline vs legacy code)
            intializeScriptEngine(source, uap);
        }

        try {
            //TODO (INF-2488): in new format, this should only happen in between contentMeta blocks/docs
            // (also should be able to use SAH _document object I think?)

            // Javascript: the user passes in 
            Object[] currField = f.getMetadata().get(m.fieldName);
            if ((null == m.flags) || m.flags.isEmpty()) {
                if (null == currField) {
                    engine.put("text", text);
                    engine.put("_iterator", null);
                }
                //(otherwise will just pass the current fields in there)
            } else { // flags specified
                if (m.flags.contains("t")) { // text
                    engine.put("text", text);
                }
                if (m.flags.contains("d")) { // entire document (minus ents and assocs)
                    GsonBuilder gb = new GsonBuilder();
                    Gson g = gb.create();
                    List<EntityPojo> ents = f.getEntities();
                    List<AssociationPojo> assocs = f.getAssociations();
                    try {
                        f.setEntities(null);
                        f.setAssociations(null);
                        engine.put("document", g.toJson(f));
                        securityManager.eval(engine, JavaScriptUtils.initScript);
                    } finally {
                        f.setEntities(ents);
                        f.setAssociations(assocs);
                    }
                }
                if (m.flags.contains("m")) { // metadata
                    GsonBuilder gb = new GsonBuilder();
                    Gson g = gb.create();
                    engine.put("_metadata", g.toJson(f.getMetadata()));
                    securityManager.eval(engine, JavaScriptUtils.iteratorMetaScript);
                }
            } //(end flags processing)

            if (null != currField) {
                f.getMetadata().remove(m.fieldName);

                GsonBuilder gb = new GsonBuilder();
                Gson g = gb.create();
                engine.put("_iterator", g.toJson(currField));
                securityManager.eval(engine, JavaScriptUtils.iteratorDocScript);
            }
            //TESTED (handling of flags, and replacing of existing fields, including when field is null but specified)

            Object returnVal = securityManager.eval(engine, m.script);

            if (null != returnVal) {
                if (returnVal instanceof String) { // The only easy case
                    Object[] array = new Object[1];
                    if ((null != m.flags) && m.flags.contains("H")) {
                        returnVal = StringEscapeUtils.unescapeHtml((String) returnVal);
                    }
                    array[0] = returnVal;
                    f.addToMetadata(m.fieldName, array);
                } else { // complex object or array - in either case the engine turns these into
                         // internal.NativeArray or internal.NativeObject

                    BasicDBList outList = JavaScriptUtils.parseNativeJsObject(returnVal, engine);
                    f.addToMetadata(m.fieldName, outList.toArray());
                }
            }
        } catch (ScriptException e) {

            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);

            // Just do nothing and log
            // e.printStackTrace();
            //DEBUG (don't output log messages per doc)
            //logger.error(e.getMessage());
        } catch (Exception e) {

            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);

            // Just do nothing and log
            // e.printStackTrace();
            //DEBUG (don't output log messages per doc)
            //logger.error(e.getMessage());
        }
    } else if (m.scriptlang.equalsIgnoreCase("xpath")) {

        String xpath = m.script;

        try {
            createHtmlCleanerIfNeeded();

            int timesToRun = 1;
            Object[] currField = null;
            if ((null != m.flags) && m.flags.contains("c")) {
                currField = f.getMetadata().get(m.fieldName);
            }
            if (null != currField) { // chained metadata
                f.getMetadata().remove(m.fieldName); // (so will add to the end)
                timesToRun = currField.length;
                text = (String) currField[0];
            } //TESTED

            for (int ii = 0; ii < timesToRun; ++ii) {
                if (ii > 0) { // (else either just text, or in the above "chained metadata" initialization above)
                    text = (String) currField[ii];
                } //TESTED

                TagNode node = cleaner.clean(new ByteArrayInputStream(text.getBytes()));

                //NewCode : Only use html cleaner for cleansing
                //use JAXP for full Xpath lib
                Document doc = new DomSerializer(new CleanerProperties()).createDOM(node);

                String extraRegex = extractRegexFromXpath(xpath);

                if (extraRegex != null)
                    xpath = xpath.replace(extraRegex, "");

                XPath xpa = XPathFactory.newInstance().newXPath();
                NodeList res = (NodeList) xpa.evaluate(xpath, doc, XPathConstants.NODESET);

                if (res.getLength() > 0) {
                    if ((null != m.flags) && (m.flags.contains("o"))) { // "o" for object
                        m.groupNum = -1; // (see bConvertToObject below)
                    }
                    StringBuffer prefix = new StringBuffer(m.fieldName).append(':');
                    int nFieldNameLen = m.fieldName.length() + 1;
                    ArrayList<Object> Llist = new ArrayList<Object>(res.getLength());
                    boolean bConvertToObject = ((m.groupNum != null) && (m.groupNum == -1));
                    boolean convertToXml = ((null != m.flags) && (m.flags.contains("x")));
                    for (int i = 0; i < res.getLength(); i++) {
                        Node info_node = res.item(i);
                        if ((null != m.flags) && (m.flags.contains("g"))) {
                            Llist.add(parseHtmlTable(info_node, m.replace));
                        } else if (bConvertToObject || convertToXml) {
                            // Try to create a JSON object out of this
                            StringWriter writer = new StringWriter();
                            try {
                                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                transformer.transform(new DOMSource(info_node), new StreamResult(writer));
                            } catch (TransformerException e1) {
                                continue;
                            }

                            if (bConvertToObject) {
                                try {
                                    JSONObject subObj = XML.toJSONObject(writer.toString());
                                    if (xpath.endsWith("*")) { // (can have any number of different names here)
                                        Llist.add(XmlToMetadataParser.convertJsonObjectToLinkedHashMap(subObj));
                                    } //TESTED
                                    else {
                                        String[] rootNames = JSONObject.getNames(subObj);
                                        if (1 == rootNames.length) {
                                            // (don't think it can't be any other number in fact)
                                            subObj = subObj.getJSONObject(rootNames[0]);
                                        }
                                        boolean bUnescapeHtml = ((null != m.flags) && m.flags.contains("H"));
                                        Llist.add(XmlToMetadataParser.convertJsonObjectToLinkedHashMap(subObj,
                                                bUnescapeHtml));
                                    } //TESTED
                                } catch (JSONException e) { // Just carry on
                                    continue;
                                }
                                //TESTED
                            } else { // leave in XML form
                                Llist.add(writer.toString().substring(38)); // +38: (step over <?xml version="1.0" encoding="UTF-8"?>)
                            } //TESTED (xpath_test.json)
                        } else { // Treat this as string, either directly or via regex
                            String info = info_node.getTextContent().trim();
                            if (extraRegex == null || extraRegex.isEmpty()) {
                                prefix.setLength(nFieldNameLen);
                                prefix.append(info);
                                String dupCheck = prefix.toString();

                                if (!regexDuplicates.contains(dupCheck)) {
                                    if ((null != m.flags) && m.flags.contains("H")) {
                                        info = StringEscapeUtils.unescapeHtml(info);
                                    }
                                    Llist.add(info);
                                    if (!bAllowDuplicates) {
                                        regexDuplicates.add(dupCheck);
                                    }
                                }
                            } else { // Apply regex to the string
                                Pattern dataRegex = createRegex(extraRegex, m.flags);
                                Matcher dataMatcher = dataRegex.matcher(info);
                                boolean result = dataMatcher.find();
                                while (result) {
                                    String toAdd;
                                    if (m.groupNum != null)
                                        toAdd = dataMatcher.group(m.groupNum);
                                    else
                                        toAdd = dataMatcher.group();
                                    prefix.setLength(nFieldNameLen);
                                    prefix.append(toAdd);
                                    String dupCheck = prefix.toString();

                                    if (!regexDuplicates.contains(dupCheck)) {
                                        if ((null != m.flags) && m.flags.contains("H")) {
                                            toAdd = StringEscapeUtils.unescapeHtml(toAdd);
                                        }
                                        Llist.add(toAdd);
                                        if (!bAllowDuplicates) {
                                            regexDuplicates.add(dupCheck);
                                        }
                                    }

                                    result = dataMatcher.find();
                                }
                            } //(regex vs no regex)
                        } //(end string vs object)
                    }
                    if (Llist.size() > 0) {
                        f.addToMetadata(m.fieldName, Llist.toArray());
                    }
                }
            } //(end loop over metadata objects if applicable)

        } catch (IOException ioe) {
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(ioe).toString(),
                    true);

            // Just do nothing and log
            //DEBUG (don't output log messages per doc)
            //logger.error(ioe.getMessage());
        } catch (ParserConfigurationException e1) {
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e1).toString(),
                    true);
            // Just do nothing and log
            //DEBUG (don't output log messages per doc)
            //logger.error(e1.getMessage());
        } catch (XPathExpressionException e1) {
            _context.getHarvestStatus().logMessage("Error evaluating xpath expression: " + xpath, true);
        }
    } else if (m.scriptlang.equalsIgnoreCase("stream")) { // XML or JSON streaming interface
        // which one?
        try {
            boolean json = false;
            boolean xml = false;
            for (int i = 0; i < 128; ++i) {
                if ('<' == text.charAt(i)) {
                    xml = true;
                    break;
                }
                if ('{' == text.charAt(i) || '[' == text.charAt(i)) {
                    json = true;
                    break;
                }
                if (!Character.isSpaceChar(text.charAt(i))) {
                    break;
                }
            } //TESTED (too many spaces: meta_stream_test, test4; incorrect chars: test3, xml: test1, json: test2)

            boolean textNotObject = m.flags == null || !m.flags.contains("o");

            List<DocumentPojo> docs = new LinkedList<DocumentPojo>();
            List<String> levelOneFields = null;
            if (null != m.script) {
                levelOneFields = Arrays.asList(m.script.split("\\s*,\\s*"));
                if ((1 == levelOneFields.size()) && levelOneFields.get(0).isEmpty()) {
                    // convert [""] to null
                    levelOneFields = null;
                }
            } //TESTED (json and xml)

            if (xml) {
                XmlToMetadataParser parser = new XmlToMetadataParser(levelOneFields, null, null, null, null,
                        null, Integer.MAX_VALUE);
                XMLInputFactory factory = XMLInputFactory.newInstance();
                factory.setProperty(XMLInputFactory.IS_COALESCING, true);
                factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                XMLStreamReader reader = null;
                try {
                    reader = factory.createXMLStreamReader(new ByteArrayInputStream(text.getBytes()));
                    docs = parser.parseDocument(reader, textNotObject);
                } finally {
                    if (null != reader)
                        reader.close();
                }
            } //TESTED (meta_stream_test, test1)
            if (json) {
                JsonReader jsonReader = null;
                try {
                    JsonToMetadataParser parser = new JsonToMetadataParser(null, levelOneFields, null, null,
                            Integer.MAX_VALUE);
                    jsonReader = new JsonReader(
                            new InputStreamReader(new ByteArrayInputStream(text.getBytes()), "UTF-8"));
                    jsonReader.setLenient(true);
                    docs = parser.parseDocument(jsonReader, textNotObject);
                } finally {
                    if (null != jsonReader)
                        jsonReader.close();
                }
            } //TESTED (meta_stream_test test2)

            if (!docs.isEmpty()) {
                ArrayList<String> Llist = null;
                ArrayList<Object> LlistObj = null;
                if (textNotObject) {
                    Llist = new ArrayList<String>(docs.size());
                } else {
                    LlistObj = new ArrayList<Object>(docs.size());
                }
                for (DocumentPojo doc : docs) {
                    if ((null != doc.getFullText()) || (null != doc.getMetadata())) {
                        if (textNotObject) {
                            Llist.add(doc.getFullText());
                        } //TESTED
                        else if (xml) {
                            LlistObj.add(doc.getMetadata());
                        } //TESTED
                        else if (json) {
                            Object o = doc.getMetadata();
                            if (null != o) {
                                o = doc.getMetadata().get("json");
                                if (o instanceof Object[]) {
                                    LlistObj.addAll(Arrays.asList((Object[]) o));
                                } else if (null != o) {
                                    LlistObj.add(o);
                                } //TESTED
                            }
                        } //TESTED
                    }
                } //TESTED
                if ((null != Llist) && !Llist.isEmpty()) {
                    f.addToMetadata(m.fieldName, Llist.toArray());
                } //TESTED
                if ((null != LlistObj) && !LlistObj.isEmpty()) {
                    f.addToMetadata(m.fieldName, LlistObj.toArray());
                } //TESTED

            } //TESTED (meta_stream_test test1,test2)
        } //(end try)
        catch (Exception e) { // various parsing errors
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);
        }
    } //TESTED (meta_stream_test)

    // (don't currently support other script types)
}

From source file:org.apache.ddlutils.io.TestDatabaseIO.java

/**
 * Tests a database model columns of all possible datatypes.
 *//* w ww .  j a  va2  s .  co m*/
public void testColumnTypes() throws Exception {
    StringBuffer modelXml = new StringBuffer();
    int[] types = TypeMap.getSuportedJdbcTypes();

    modelXml.append("<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='test'>\n");
    modelXml.append("  <table name='SomeTable'\n");
    modelXml.append("         description='Some table'>\n");
    for (int idx = 0; idx < types.length; idx++) {
        modelXml.append("    <column name='ID");
        modelXml.append(idx);
        modelXml.append("' type='");
        modelXml.append(TypeMap.getJdbcTypeName(types[idx]));
        modelXml.append("'/>\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>");

    Database model = readModel(modelXml.toString());

    assertEquals("test", model.getName());
    assertEquals(1, model.getTableCount());

    Table table = model.getTable(0);

    assertEquals("SomeTable", "Some table", types.length, 0, 0, 0, 0, table);

    for (int idx = 0; idx < types.length; idx++) {
        assertEquals("ID" + idx, types[idx], 0, 0, null, null, null, false, false, false, table.getColumn(idx));
    }

    modelXml.setLength(0);
    modelXml.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    modelXml.append("<database xmlns=\"" + DatabaseIO.DDLUTILS_NAMESPACE + "\" name=\"test\">\n");
    modelXml.append("  <table name=\"SomeTable\" description=\"Some table\">\n");
    for (int idx = 0; idx < types.length; idx++) {
        modelXml.append("    <column name=\"ID");
        modelXml.append(idx);
        modelXml.append("\" primaryKey=\"false\" required=\"false\" type=\"");
        modelXml.append(TypeMap.getJdbcTypeName(types[idx]));
        modelXml.append("\" autoIncrement=\"false\" />\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>\n");

    assertEquals(modelXml.toString(), model);
}

From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java

@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    if (rolesOnly) {
        throw new ProvisioningException("Unsupported");
    }/*from w  w w.ja va  2  s.c om*/

    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    KSUser newUser = new KSUser();
    newUser.setDomain_id(this.usersDomain);
    newUser.setName(user.getUserID());
    newUser.setEnabled(true);

    if (attributes.contains("email") && user.getAttribs().containsKey("email")) {
        newUser.setEmail(user.getAttribs().get("email").getValues().get(0));
    }

    if (attributes.contains("description") && user.getAttribs().containsKey("description")) {
        newUser.setEmail(user.getAttribs().get("description").getValues().get(0));
    }

    HttpCon con = null;
    KSUser fromKS = null;
    try {
        con = this.createClient();
        KSToken token = this.getToken(con);
        Gson gson = new Gson();
        UserHolder userHolder = new UserHolder();
        userHolder.setUser(newUser);
        String json = gson.toJson(userHolder);

        StringBuffer b = new StringBuffer();
        b.append(this.url).append("/users");
        json = this.callWSPost(token.getAuthToken(), con, b.toString(), json);
        if (json == null) {
            throw new Exception("Could not create user");
        }

        UserHolder createdUser = gson.fromJson(json, UserHolder.class);

        if (createdUser.getUser() == null) {
            throw new ProvisioningException("Could not create user :" + json);
        }

        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), true, ActionType.Add, approvalID,
                workflow, "name", user.getUserID());
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID,
                workflow, "name", user.getUserID());
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID,
                workflow, "domain_id", this.usersDomain);
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID,
                workflow, "enabled", "true");
        if (attributes.contains("email")) {
            this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID,
                    workflow, "email", user.getAttribs().get("email").getValues().get(0));
        }
        if (attributes.contains("description")) {
            this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID,
                    workflow, "description", user.getAttribs().get("description").getValues().get(0));
        }

        for (String group : user.getGroups()) {
            String groupID = this.getGroupID(token.getAuthToken(), con, group);
            b.setLength(0);
            b.append(this.url).append("/groups/").append(groupID).append("/users/")
                    .append(createdUser.getUser().getId());
            if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add,
                        approvalID, workflow, "group", group);

            } else {
                throw new ProvisioningException("Could not add group " + group);
            }

        }

        if (attributes.contains("roles")) {
            Attribute roles = user.getAttribs().get("roles");
            for (String roleJSON : roles.getValues()) {
                Role role = gson.fromJson(roleJSON, Role.class);
                if (role.getScope().equalsIgnoreCase("project")) {
                    String projectid = this.getProjectID(token.getAuthToken(), con, role.getProject());
                    if (projectid == null) {
                        throw new ProvisioningException("Project " + role.getDomain() + " does not exist");
                    }

                    String roleid = this.getRoleID(token.getAuthToken(), con, role.getName());
                    if (roleid == null) {
                        throw new ProvisioningException("Role " + role.getName() + " does not exist");
                    }

                    b.setLength(0);
                    b.append(this.url).append("/projects/").append(projectid).append("/users/")
                            .append(createdUser.getUser().getId()).append("/roles/").append(roleid);

                    if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add,
                                approvalID, workflow, "role", roleJSON);
                    } else {
                        throw new ProvisioningException("Could not add role " + roleJSON);
                    }
                } else {
                    String domainid = this.getDomainID(token.getAuthToken(), con, role.getDomain());
                    if (domainid == null) {
                        throw new ProvisioningException("Domain " + role.getDomain() + " does not exist");
                    }

                    String roleid = this.getRoleID(token.getAuthToken(), con, role.getName());
                    if (roleid == null) {
                        throw new ProvisioningException("Role " + role.getName() + " does not exist");
                    }

                    b.setLength(0);
                    b.append(this.url).append("/domains/").append(domainid).append("/users/")
                            .append(createdUser.getUser().getId()).append("/roles/").append(roleid);

                    if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add,
                                approvalID, workflow, "role", roleJSON);
                    } else {
                        throw new ProvisioningException("Could not add role " + roleJSON);
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new ProvisioningException("Could not work with keystone", e);
    } finally {
        if (con != null) {
            con.getBcm().shutdown();
        }
    }
}

From source file:org.apache.struts.taglib.TagUtils.java

/**
 * Compute a hyperlink URL based on the <code>forward</code>,
 * <code>href</code>, <code>action</code> or <code>page</code> parameter
 * that is not null. The returned URL will have already been passed to
 * <code>response.encodeURL()</code> for adding a session identifier.
 *
 * @param pageContext      PageContext for the tag making this call
 * @param forward          Logical forward name for which to look up the
 *                         context-relative URI (if specified)
 * @param href             URL to be utilized unmodified (if specified)
 * @param page             Module-relative page for which a URL should be
 *                         created (if specified)
 * @param action           Logical action name for which to look up the
 *                         context-relative URI (if specified)
 * @param params           Map of parameters to be dynamically included
 *                         (if any)//from  ww w. ja v a  2  s .  c o  m
 * @param anchor           Anchor to be dynamically included (if any)
 * @param redirect         Is this URL for a <code>response.sendRedirect()</code>?
 * @param encodeSeparator  This is only checked if redirect is set to
 *                         false (never encoded for a redirect).  If true,
 *                         query string parameter separators are encoded
 *                         as &gt;amp;, else &amp; is used.
 * @param useLocalEncoding If set to true, urlencoding is done on the
 *                         bytes of character encoding from
 *                         ServletResponse#getCharacterEncoding. Use UTF-8
 *                         otherwise.
 * @return URL with session identifier
 * @throws java.net.MalformedURLException if a URL cannot be created for
 *                                        the specified parameters
 */
public String computeURLWithCharEncoding(PageContext pageContext, String forward, String href, String page,
        String action, String module, Map params, String anchor, boolean redirect, boolean encodeSeparator,
        boolean useLocalEncoding) throws MalformedURLException {
    String charEncoding = "UTF-8";

    if (useLocalEncoding) {
        charEncoding = pageContext.getResponse().getCharacterEncoding();
    }

    // TODO All the computeURL() methods need refactoring!
    // Validate that exactly one specifier was included
    int n = 0;

    if (forward != null) {
        n++;
    }

    if (href != null) {
        n++;
    }

    if (page != null) {
        n++;
    }

    if (action != null) {
        n++;
    }

    if (n != 1) {
        throw new MalformedURLException(messages.getMessage("computeURL.specifier"));
    }

    // Look up the module configuration for this request
    ModuleConfig moduleConfig = getModuleConfig(module, pageContext);

    // Calculate the appropriate URL
    StringBuffer url = new StringBuffer();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    if (forward != null) {
        ForwardConfig forwardConfig = moduleConfig.findForwardConfig(forward);

        if (forwardConfig == null) {
            throw new MalformedURLException(messages.getMessage("computeURL.forward", forward));
        }

        // **** removed - see bug 37817 ****
        //  if (forwardConfig.getRedirect()) {
        //      redirect = true;
        //  }

        if (forwardConfig.getPath().startsWith("/")) {
            url.append(request.getContextPath());
            url.append(RequestUtils.forwardURL(request, forwardConfig, moduleConfig));
        } else {
            url.append(forwardConfig.getPath());
        }
    } else if (href != null) {
        url.append(href);
    } else if (action != null) {
        ActionServlet servlet = (ActionServlet) pageContext.getServletContext()
                .getAttribute(Globals.ACTION_SERVLET_KEY);
        String actionIdPath = RequestUtils.actionIdURL(action, moduleConfig, servlet);
        if (actionIdPath != null) {
            action = actionIdPath;
            url.append(request.getContextPath());
            url.append(actionIdPath);
        } else {
            url.append(instance.getActionMappingURL(action, module, pageContext, false));
        }
    } else /* if (page != null) */
    {
        url.append(request.getContextPath());
        url.append(this.pageURL(request, page, moduleConfig));
    }

    // Add anchor if requested (replacing any existing anchor)
    if (anchor != null) {
        String temp = url.toString();
        int hash = temp.indexOf('#');

        if (hash >= 0) {
            url.setLength(hash);
        }

        url.append('#');
        url.append(this.encodeURL(anchor, charEncoding));
    }

    // Add dynamic parameters if requested
    if ((params != null) && (params.size() > 0)) {
        // Save any existing anchor
        String temp = url.toString();
        int hash = temp.indexOf('#');

        if (hash >= 0) {
            anchor = temp.substring(hash + 1);
            url.setLength(hash);
            temp = url.toString();
        } else {
            anchor = null;
        }

        // Define the parameter separator
        String separator = null;

        if (redirect) {
            separator = "&";
        } else if (encodeSeparator) {
            separator = "&amp;";
        } else {
            separator = "&";
        }

        // Add the required request parameters
        boolean question = temp.indexOf('?') >= 0;
        Iterator keys = params.keySet().iterator();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object value = params.get(key);

            if (value == null) {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('='); // Interpret null as "no value"
            } else if (value instanceof String) {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('=');
                url.append(this.encodeURL((String) value, charEncoding));
            } else if (value instanceof String[]) {
                String[] values = (String[]) value;

                for (int i = 0; i < values.length; i++) {
                    if (!question) {
                        url.append('?');
                        question = true;
                    } else {
                        url.append(separator);
                    }

                    url.append(this.encodeURL(key, charEncoding));
                    url.append('=');
                    url.append(this.encodeURL(values[i], charEncoding));
                }
            } else /* Convert other objects to a string */
            {
                if (!question) {
                    url.append('?');
                    question = true;
                } else {
                    url.append(separator);
                }

                url.append(this.encodeURL(key, charEncoding));
                url.append('=');
                url.append(this.encodeURL(value.toString(), charEncoding));
            }
        }

        // Re-add the saved anchor (if any)
        if (anchor != null) {
            url.append('#');
            url.append(this.encodeURL(anchor, charEncoding));
        }
    }

    // Perform URL rewriting to include our session ID (if any)
    // but only if url is not an external URL
    if ((href == null) && (pageContext.getSession() != null)) {
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

        if (redirect) {
            return (response.encodeRedirectURL(url.toString()));
        }

        return (response.encodeURL(url.toString()));
    }

    return (url.toString());
}

From source file:org.apache.axis.transport.http.SimpleAxisWorker.java

/**
 * The main workhorse method.//w  ww .jav  a 2  s.c o  m
 */
public void execute() {
    byte buf[] = new byte[BUFSIZ];
    // create an Axis server
    AxisServer engine = server.getAxisServer();

    // create and initialize a message context
    MessageContext msgContext = new MessageContext(engine);
    Message requestMsg = null;

    // Reusuable, buffered, content length controlled, InputStream
    NonBlockingBufferedInputStream is = new NonBlockingBufferedInputStream();

    // buffers for the headers we care about
    StringBuffer soapAction = new StringBuffer();
    StringBuffer httpRequest = new StringBuffer();
    StringBuffer fileName = new StringBuffer();
    StringBuffer cookie = new StringBuffer();
    StringBuffer cookie2 = new StringBuffer();
    StringBuffer authInfo = new StringBuffer();
    StringBuffer contentType = new StringBuffer();
    StringBuffer contentLocation = new StringBuffer();

    Message responseMsg = null;

    // prepare request (do as much as possible while waiting for the
    // next connection).  Note the next two statements are commented
    // out.  Uncomment them if you experience any problems with not
    // resetting state between requests:
    //   msgContext = new MessageContext();
    //   requestMsg = new Message("", "String");
    //msgContext.setProperty("transport", "HTTPTransport");
    msgContext.setTransportName(transportName);

    responseMsg = null;

    try {
        // assume the best
        byte[] status = OK;

        // assume we're not getting WSDL
        boolean doWsdl = false;

        // cookie for this session, if any
        String cooky = null;

        String methodName = null;

        try {
            // wipe cookies if we're doing sessions
            if (server.isSessionUsed()) {
                cookie.delete(0, cookie.length());
                cookie2.delete(0, cookie2.length());
            }
            authInfo.delete(0, authInfo.length());

            // read headers
            is.setInputStream(socket.getInputStream());
            // parse all headers into hashtable
            MimeHeaders requestHeaders = new MimeHeaders();
            int contentLength = parseHeaders(is, buf, contentType, contentLocation, soapAction, httpRequest,
                    fileName, cookie, cookie2, authInfo, requestHeaders);
            is.setContentLength(contentLength);

            int paramIdx = fileName.toString().indexOf('?');
            if (paramIdx != -1) {
                // Got params
                String params = fileName.substring(paramIdx + 1);
                fileName.setLength(paramIdx);

                log.debug(Messages.getMessage("filename00", fileName.toString()));
                log.debug(Messages.getMessage("params00", params));

                if ("wsdl".equalsIgnoreCase(params))
                    doWsdl = true;

                if (params.startsWith("method=")) {
                    methodName = params.substring(7);
                }
            }

            // Real and relative paths are the same for the
            // SimpleAxisServer
            msgContext.setProperty(Constants.MC_REALPATH, fileName.toString());
            msgContext.setProperty(Constants.MC_RELATIVE_PATH, fileName.toString());
            msgContext.setProperty(Constants.MC_JWS_CLASSDIR, "jwsClasses");
            msgContext.setProperty(Constants.MC_HOME_DIR, ".");

            // !!! Fix string concatenation
            String url = "http://" + getLocalHost() + ":" + server.getServerSocket().getLocalPort() + "/"
                    + fileName.toString();
            msgContext.setProperty(MessageContext.TRANS_URL, url);

            String filePart = fileName.toString();
            if (filePart.startsWith("axis/services/")) {
                String servicePart = filePart.substring(14);
                int separator = servicePart.indexOf('/');
                if (separator > -1) {
                    msgContext.setProperty("objectID", servicePart.substring(separator + 1));
                    servicePart = servicePart.substring(0, separator);
                }
                msgContext.setTargetService(servicePart);
            }

            if (authInfo.length() > 0) {
                // Process authentication info
                //authInfo = new StringBuffer("dXNlcjE6cGFzczE=");
                byte[] decoded = Base64.decode(authInfo.toString());
                StringBuffer userBuf = new StringBuffer();
                StringBuffer pwBuf = new StringBuffer();
                StringBuffer authBuf = userBuf;
                for (int i = 0; i < decoded.length; i++) {
                    if ((char) (decoded[i] & 0x7f) == ':') {
                        authBuf = pwBuf;
                        continue;
                    }
                    authBuf.append((char) (decoded[i] & 0x7f));
                }

                if (log.isDebugEnabled()) {
                    log.debug(Messages.getMessage("user00", userBuf.toString()));
                }

                msgContext.setUsername(userBuf.toString());
                msgContext.setPassword(pwBuf.toString());
            }

            // if get, then return simpleton document as response
            if (httpRequest.toString().equals("GET")) {

                OutputStream out = socket.getOutputStream();
                out.write(HTTP);
                if (fileName.length() == 0) {
                    out.write("301 Redirect\nLocation: /axis/\n\n".getBytes());
                    out.flush();
                    return;
                }
                out.write(status);

                if (methodName != null) {
                    String body = "<" + methodName + ">" +
                    //                               args +
                            "</" + methodName + ">";
                    String msgtxt = "<SOAP-ENV:Envelope" + " xmlns:SOAP-ENV=\"" + Constants.URI_SOAP12_ENV
                            + "\">" + "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";

                    ByteArrayInputStream istream = new ByteArrayInputStream(msgtxt.getBytes());
                    requestMsg = new Message(istream);
                } else if (doWsdl) {
                    engine.generateWSDL(msgContext);

                    Document doc = (Document) msgContext.getProperty("WSDL");
                    if (doc != null) {
                        XMLUtils.normalize(doc.getDocumentElement());
                        String response = XMLUtils.PrettyDocumentToString(doc);
                        byte[] respBytes = response.getBytes();

                        out.write(XML_MIME_STUFF);
                        putInt(buf, out, respBytes.length);
                        out.write(SEPARATOR);
                        out.write(respBytes);
                        out.flush();
                        return;
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append("<h2>And now... Some Services</h2>\n");
                    Iterator i = engine.getConfig().getDeployedServices();
                    sb.append("<ul>\n");
                    while (i.hasNext()) {
                        ServiceDesc sd = (ServiceDesc) i.next();
                        sb.append("<li>\n");
                        sb.append(sd.getName());
                        sb.append(" <a href=\"services/");
                        sb.append(sd.getName());
                        sb.append("?wsdl\"><i>(wsdl)</i></a></li>\n");
                        ArrayList operations = sd.getOperations();
                        if (!operations.isEmpty()) {
                            sb.append("<ul>\n");
                            for (Iterator it = operations.iterator(); it.hasNext();) {
                                OperationDesc desc = (OperationDesc) it.next();
                                sb.append("<li>" + desc.getName());
                            }
                            sb.append("</ul>\n");
                        }
                    }
                    sb.append("</ul>\n");

                    byte[] bytes = sb.toString().getBytes();

                    out.write(HTML_MIME_STUFF);
                    putInt(buf, out, bytes.length);
                    out.write(SEPARATOR);
                    out.write(bytes);
                    out.flush();
                    return;
                }
            } else {

                // this may be "" if either SOAPAction: "" or if no SOAPAction at all.
                // for now, do not complain if no SOAPAction at all
                String soapActionString = soapAction.toString();
                if (soapActionString != null) {
                    msgContext.setUseSOAPAction(true);
                    msgContext.setSOAPActionURI(soapActionString);
                }
                requestMsg = new Message(is, false, contentType.toString(), contentLocation.toString());
            }

            // Transfer HTTP headers to MIME headers for request message.
            MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
            for (Iterator i = requestHeaders.getAllHeaders(); i.hasNext();) {
                MimeHeader requestHeader = (MimeHeader) i.next();
                requestMimeHeaders.addHeader(requestHeader.getName(), requestHeader.getValue());
            }
            msgContext.setRequestMessage(requestMsg);
            // put character encoding of request to message context
            // in order to reuse it during the whole process.   
            String requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }

            // set up session, if any
            if (server.isSessionUsed()) {
                // did we get a cookie?
                if (cookie.length() > 0) {
                    cooky = cookie.toString().trim();
                } else if (cookie2.length() > 0) {
                    cooky = cookie2.toString().trim();
                }

                // if cooky is null, cook up a cooky
                if (cooky == null) {
                    // fake one up!
                    // make it be an arbitrarily increasing number
                    // (no this is not thread safe because ++ isn't atomic)
                    int i = SimpleAxisServer.sessionIndex++;
                    cooky = "" + i;
                }

                msgContext.setSession(server.createSession(cooky));
            }

            // invoke the Axis engine
            engine.invoke(msgContext);

            // Retrieve the response from Axis
            responseMsg = msgContext.getResponseMessage();

            if (responseMsg == null) {
                status = NOCONTENT;
            }
        } catch (Exception e) {
            AxisFault af;
            if (e instanceof AxisFault) {
                af = (AxisFault) e;
                log.debug(Messages.getMessage("serverFault00"), af);
                QName faultCode = af.getFaultCode();
                if (Constants.FAULT_SOAP12_SENDER.equals(faultCode)) {
                    status = SENDER;
                } else if ("Server.Unauthorized".equals(af.getFaultCode().getLocalPart())) {
                    status = UNAUTH; // SC_UNAUTHORIZED
                } else {
                    status = ISE; // SC_INTERNAL_SERVER_ERROR
                }
            } else {
                status = ISE; // SC_INTERNAL_SERVER_ERROR
                af = AxisFault.makeFault(e);
            }

            // There may be headers we want to preserve in the
            // response message - so if it's there, just add the
            // FaultElement to it.  Otherwise, make a new one.
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(af);
                responseMsg.setMessageContext(msgContext);
            } else {
                try {
                    SOAPEnvelope env = responseMsg.getSOAPEnvelope();
                    env.clearBody();
                    env.addBodyElement(new SOAPFault((AxisFault) e));
                } catch (AxisFault fault) {
                    // Should never reach here!
                }
            }
        }

        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null && responseMsg != null) {
            responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
        }
        // Send it on its way...
        OutputStream out = socket.getOutputStream();
        out.write(HTTP);
        out.write(status);

        if (responseMsg != null) {
            if (server.isSessionUsed() && null != cooky && 0 != cooky.trim().length()) {
                // write cookie headers, if any
                // don't sweat efficiency *too* badly
                // optimize at will
                StringBuffer cookieOut = new StringBuffer();
                cookieOut.append("\r\nSet-Cookie: ").append(cooky).append("\r\nSet-Cookie2: ").append(cooky);
                // OH, THE HUMILITY!  yes this is inefficient.
                out.write(cookieOut.toString().getBytes());
            }

            //out.write(XML_MIME_STUFF);
            out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_TYPE + ": "
                    + responseMsg.getContentType(msgContext.getSOAPConstants())).getBytes());
            // Writing the length causes the entire message to be decoded twice.
            //out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_LENGTH + ": " + responseMsg.getContentLength()).getBytes());
            // putInt(out, response.length);

            // Transfer MIME headers to HTTP headers for response message.
            for (Iterator i = responseMsg.getMimeHeaders().getAllHeaders(); i.hasNext();) {
                MimeHeader responseHeader = (MimeHeader) i.next();
                out.write('\r');
                out.write('\n');
                out.write(responseHeader.getName().getBytes());
                out.write(headerEnder);
                out.write(responseHeader.getValue().getBytes());
            }

            out.write(SEPARATOR);
            responseMsg.writeTo(out);
        }

        // out.write(response);
        out.flush();
    } catch (Exception e) {
        log.info(Messages.getMessage("exception00"), e);
    } finally {
        try {
            if (socket != null)
                socket.close();
        } catch (Exception e) {
        }
    }
    if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
        // why then, quit!
        try {
            server.stop();
        } catch (Exception e) {
        }
    }

}

From source file:com.pureinfo.studio.db.xls2srm.impl.XlsImportRunner.java

/**
 * Converts the properties whose type are different from SRM.
 * //w w w.  jav a2 s.  c om
 * @param _oldObj
 * @param _newObj
 * @throws Exception
 */
private boolean convert(DolphinObject _oldObj, DolphinObject _newObj, List _errorDataList, int _nChooseIfRepeat)
        throws Exception {
    Element convert = m_xmlConfig.element("data");
    List properties = convert.element("convert").elements();
    Element element;
    String sFrom, sTo, sRef, sForeignKey;
    Object value = null;
    Object valueFrom = null;
    boolean bConvertError = false;
    boolean bvalidate = true;

    for (int i = 0; i < properties.size(); i++) {
        element = (Element) properties.get(i);
        logger.debug(
                element.attributeValue("from") + ":" + _oldObj.getProperty(element.attributeValue("from")));
        if (element.attributeValue("provider") != null) {
            sRef = element.attributeValue("ref");
            sFrom = element.attributeValue("from");
            sTo = element.attributeValue("to");
            if (sRef != null && sRef.charAt(0) == '#') {
                // if ( _nChooseIfRepeat != Xls2srmForm.JUSTFORCHECK
                IImportorRef ref = (IImportorRef) PureFactory.getBean(sRef.substring(1));

                value = ref.convert(_oldObj, _newObj, sFrom, String.valueOf(_nChooseIfRepeat), null,
                        LocalContextHelper.currentSession("Local"), m_entityMetadata,
                        m_xmlConfig.elementTextTrim("match-properties"), m_xmlConfig.attributeValue("temp"));

                _newObj.setProperty(sTo, value);
                checkIsValidPatent(_newObj, _errorDataList);
                continue;
            }

            continue;
        }
        // sFrom = element.attributeValue("from").toUpperCase();
        sFrom = element.attributeValue("from");
        sTo = element.attributeValue("to");
        sRef = element.attributeValue("ref");

        // to convert property value
        if (!_oldObj.hasProperty(sFrom)) {
            continue;
            // throw new PureException(PureException.PROPERTY_NOTFOUND,
            // sFrom);
        }
        if (isPropertySet(_newObj, sTo))
            continue; // skip

        // else
        try {
            sForeignKey = element.attributeValue("fk");
            String expandCondition = null, expandPropertyDebug = null;
            StringBuffer expandConditionBuffer = new StringBuffer();
            StringBuffer expandPropertyDebugBuffer = new StringBuffer();
            Element expandElement;
            List expands = element.elements("expand");
            if (expands.size() > 0) {
                for (int j = 0; j < expands.size(); j++) {
                    expandElement = (Element) expands.get(i);
                    String expandPropertyValue = _oldObj.getProperty(expandElement.attributeValue("from"))
                            .toString();
                    expandConditionBuffer.append(" " + expandElement.attributeValue("to"));
                    expandConditionBuffer.append("=");
                    expandConditionBuffer.append(expandPropertyValue);
                    expandConditionBuffer.append(" and ");
                    expandPropertyDebugBuffer.append("(" + expandElement.attributeValue("from") + "\""
                            + expandPropertyValue + "\"" + ")");
                }
            }
            if (expandConditionBuffer.length() > 0) {
                expandCondition = expandConditionBuffer.toString();
                expandPropertyDebug = expandPropertyDebugBuffer.toString();
            }
            expandConditionBuffer.setLength(0);

            valueFrom = _oldObj.getProperty(sFrom);
            if (element.attributeValue("subString") != null) {
                String sSubStringValue = element.attributeValue("subString");
                int nBeganIndex = 0;
                int nEndIndex = sSubStringValue.length() - 1;

                if (sSubStringValue.indexOf(",") > 0) {
                    String sBeganIndex = sSubStringValue.substring(0, sSubStringValue.indexOf(","));
                    nBeganIndex = Integer.parseInt(sBeganIndex);

                    String sEndIndex = sSubStringValue.substring(sSubStringValue.indexOf(",") + 1);

                    nEndIndex = Integer.parseInt(sEndIndex);
                    // logger.debug(""+nBeganIndex+""+nEndIndex);
                }
                if (valueFrom != null && ((String) valueFrom).length() >= nEndIndex) {
                    valueFrom = ((String) valueFrom).substring(nBeganIndex, nEndIndex);
                    // logger.debug(" "+valueFrom);
                }
            }

            if (element.attributeValue("validate") != null
                    && element.attributeValue("validate").equals("false"))
                bvalidate = false;
            value = this.lookupRefValue(sRef, valueFrom, sForeignKey, sFrom, _errorDataList, expandCondition,
                    expandPropertyDebug, bvalidate);
            if (value == null) {
                bConvertError = true;
            } else {
                _newObj.setProperty(sTo, value);
                System.out.println("=======" + _newObj.getProperty(sTo));
            }

        } catch (Exception ex) {
            throw new PureException(PureException.INVALID_VALUE,
                    "convert " + sFrom + "[" + value + "] to " + sTo, ex);
        }

    }

    return bConvertError;
}

From source file:org.geotools.jdbc.JoiningJDBCFeatureSource.java

/**
 * Generates a 'SELECT p1, p2, ... FROM ... WHERE ...' prepared statement.
 * /*from   w w  w .j  a v a  2  s .  co  m*/
 * @param featureType
 *            the feature type that the query must return (may contain less attributes than the
 *            native one)
 * @param attributes
 *            the properties queried, or {@link Query#ALL_NAMES} to gather all of them
 * @param query
 *            the query to be run. The type name and property will be ignored, as they are
 *            supposed to have been already embedded into the provided feature type
 * @param cx
 *            The database connection to be used to create the prepared statement
 * @throws SQLException 
 * @throws IOException 
 * @throws FilterToSQLException
 */
protected String selectSQL(SimpleFeatureType featureType, JoiningQuery query,
        AtomicReference<PreparedFilterToSQL> toSQLref) throws IOException, SQLException, FilterToSQLException {

    // first we create from clause, for aliases

    StringBuffer fromclause = new StringBuffer();
    getDataStore().encodeTableName(featureType.getTypeName(), fromclause, query.getHints());

    //joining
    Set<String> tableNames = new HashSet<String>();

    String lastTypeName = featureType.getTypeName();
    String curTypeName = lastTypeName;

    String[] aliases = null;

    if (query.getQueryJoins() != null) {

        aliases = new String[query.getQueryJoins().size()];

        for (int i = 0; i < query.getQueryJoins().size(); i++) {
            JoiningQuery.QueryJoin join = query.getQueryJoins().get(i);

            fromclause.append(" INNER JOIN ");
            String alias = null;

            FilterToSQL toSQL1 = createFilterToSQL(getDataStore().getSchema(lastTypeName));
            FilterToSQL toSQL2 = createFilterToSQL(getDataStore().getSchema(join.getJoiningTypeName()));

            String last_alias = createAlias(lastTypeName, tableNames);
            tableNames.add(last_alias);
            curTypeName = last_alias;
            if (tableNames.contains(join.getJoiningTypeName())) {
                alias = createAlias(join.getJoiningTypeName(), tableNames);

                aliases[i] = alias;

                getDataStore().encodeTableName(join.getJoiningTypeName(), fromclause, query.getHints());
                fromclause.append(" ");
                getDataStore().dialect.encodeTableName(alias, fromclause);
                fromclause.append(" ON ( ");

                toSQL2.setFieldEncoder(new JoiningFieldEncoder(alias));
                fromclause.append(toSQL2.encodeToString(join.getForeignKeyName()));

            } else {
                aliases[i] = null;
                getDataStore().encodeTableName(join.getJoiningTypeName(), fromclause, query.getHints());
                fromclause.append(" ON ( ");
                toSQL2.setFieldEncoder(new JoiningFieldEncoder(join.getJoiningTypeName()));
                fromclause.append(toSQL2.encodeToString(join.getForeignKeyName()));
            }
            fromclause.append(" = ");
            toSQL1.setFieldEncoder(new JoiningFieldEncoder(curTypeName));
            fromclause.append(toSQL1.encodeToString(join.getJoiningKeyName()));
            fromclause.append(") ");
            lastTypeName = join.getJoiningTypeName();
            curTypeName = alias == null ? lastTypeName : alias;
        }
    }

    //begin sql
    StringBuffer sql = new StringBuffer();
    sql.append("SELECT ");

    // primary key
    PrimaryKey key = null;

    try {
        key = getDataStore().getPrimaryKey(featureType);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Set<String> pkColumnNames = new HashSet<String>();
    String colName;
    for (PrimaryKeyColumn col : key.getColumns()) {
        colName = col.getName();
        encodeColumnName(colName, featureType.getTypeName(), sql, query.getHints());
        sql.append(",");
        pkColumnNames.add(colName);
    }

    //other columns
    for (AttributeDescriptor att : featureType.getAttributeDescriptors()) {
        // skip the eventually exposed pk column values
        String columnName = att.getLocalName();
        if (pkColumnNames.contains(columnName))
            continue;

        if (att instanceof GeometryDescriptor) {
            //encode as geometry
            encodeGeometryColumn((GeometryDescriptor) att, featureType.getTypeName(), sql, query.getHints());

            //alias it to be the name of the original geometry
            getDataStore().dialect.encodeColumnAlias(columnName, sql);
        } else {
            encodeColumnName(columnName, featureType.getTypeName(), sql, query.getHints());

        }

        sql.append(",");
    }

    if (query.getQueryJoins() != null && query.getQueryJoins().size() > 0) {
        for (int i = 0; i < query.getQueryJoins().size(); i++) {
            for (int j = 0; j < query.getQueryJoins().get(i).getSortBy().length; j++) {
                if (aliases[i] != null) {
                    getDataStore().dialect.encodeColumnName(aliases[i],
                            query.getQueryJoins().get(i).getSortBy()[j].getPropertyName().getPropertyName(),
                            sql);
                } else {
                    encodeColumnName(
                            query.getQueryJoins().get(i).getSortBy()[j].getPropertyName().getPropertyName(),
                            query.getQueryJoins().get(i).getJoiningTypeName(), sql, query.getHints());

                }
                sql.append(" ").append(FOREIGN_ID + "_" + i + "_" + j).append(",");
            }
        }
    }

    sql.setLength(sql.length() - 1);

    sql.append(" FROM ");

    sql.append(fromclause);

    //filtering
    FilterToSQL toSQL = null;
    Filter filter = query.getFilter();
    if (filter != null && !Filter.INCLUDE.equals(filter)) {
        //encode filter
        try {
            SortBy[] lastSortBy = null;
            // leave it as null if it's asking for a subset, since we don't want to join to get
            // other rows of same id
            // since we don't want a full feature, but a subset only
            if (!query.isSubset()) {
                // grab the full feature type, as we might be encoding a filter
                // that uses attributes that aren't returned in the results
                lastSortBy = query.getQueryJoins() == null || query.getQueryJoins().size() == 0
                        ? query.getSortBy()
                        : query.getQueryJoins().get(query.getQueryJoins().size() - 1).getSortBy();
            }
            String lastTableName = query.getQueryJoins() == null || query.getQueryJoins().size() == 0
                    ? query.getTypeName()
                    : query.getQueryJoins().get(query.getQueryJoins().size() - 1).getJoiningTypeName();
            String lastTableAlias = query.getQueryJoins() == null || query.getQueryJoins().size() == 0
                    ? query.getTypeName()
                    : aliases[query.getQueryJoins().size() - 1] == null ? lastTableName
                            : aliases[query.getQueryJoins().size() - 1];

            toSQL = createFilterToSQL(getDataStore().getSchema(lastTableName));

            if (lastSortBy != null) {
                //we will use another join for the filter
                //assuming that the last sort by specifies the ID of the parent feature                   
                //this way we will ensure that if the table is denormalized, that all rows
                //with the same ID are included (for multi-valued features)

                sql.append(" INNER JOIN ( SELECT DISTINCT ");
                for (int i = 0; i < lastSortBy.length; i++) {
                    getDataStore().dialect.encodeColumnName(null,
                            lastSortBy[i].getPropertyName().getPropertyName(), sql);
                    if (i < lastSortBy.length - 1)
                        sql.append(",");
                }
                sql.append(" FROM ");
                getDataStore().encodeTableName(lastTableName, sql, query.getHints());
                sql.append(" ").append(toSQL.encodeToString(filter));
                sql.append(" ) " + TEMP_FILTER_ALIAS);
                sql.append(" ON ( ");
                for (int i = 0; i < lastSortBy.length; i++) {
                    encodeColumnName2(lastSortBy[i].getPropertyName().getPropertyName(), lastTableAlias, sql,
                            null);
                    sql.append(" = ");
                    encodeColumnName2(lastSortBy[i].getPropertyName().getPropertyName(), TEMP_FILTER_ALIAS, sql,
                            null);
                    if (i < lastSortBy.length - 1)
                        sql.append(" AND ");
                }
                sql.append(" ) ");
            } else {
                toSQL.setFieldEncoder(new JoiningFieldEncoder(curTypeName));
                sql.append(" ").append(toSQL.encodeToString(filter));
            }
        } catch (FilterToSQLException e) {
            throw new RuntimeException(e);
        }
    }

    //sorting
    sort(query, sql, aliases, pkColumnNames);

    // finally encode limit/offset, if necessary
    getDataStore().applyLimitOffset(sql, query);

    if (toSQLref != null && toSQL instanceof PreparedFilterToSQL) {
        toSQLref.set((PreparedFilterToSQL) toSQL);
    }

    return sql.toString();
}

From source file:com.vladium.emma.report.html.ReportGenerator.java

public Object visit(final AllItem item, final Object ctx) {
    HTMLWriter out = null;//  www  . ja v  a2  s. c  o m
    try {
        File outFile = m_settings.getOutFile();
        if (outFile == null) {
            outFile = new File("index".concat(FILE_EXTENSION));
            m_settings.setOutFile(outFile);
        }

        final File fullOutFile = Files.newFile(m_settings.getOutDir(), outFile);

        m_log.info("writing [" + getType() + "] report to [" + fullOutFile.getAbsolutePath() + "] ...");

        out = openOutFile(fullOutFile, m_settings.getOutEncoding(), true);

        final int[] columns = m_settings.getColumnOrder();
        final StringBuffer buf = new StringBuffer();

        final String title;
        {
            final StringBuffer _title = new StringBuffer(REPORT_HEADER_TITLE);

            _title.append(" (generated ");
            _title.append(new Date(EMMAProperties.getTimeStamp()));
            _title.append(')');

            title = _title.toString();
        }

        final HTMLDocument page = createPage(title);
        {
            final IItem[] path = getParentPath(item);

            addPageHeader(page, item, path);
            addPageFooter(page, item, path);
        }

        // [all] coverage summary table:

        page.addH(1, "OVERALL COVERAGE SUMMARY", null);

        final HTMLTable summaryTable = new HTMLTable("100%", null, null, "0");
        {
            // header row:
            final HTMLTable.IRow header = summaryTable.newTitleRow();
            // coverage row:
            final HTMLTable.IRow coverage = summaryTable.newRow();

            for (int c = 0; c < columns.length; ++c) {
                final int attrID = columns[c];
                final IItemAttribute attr = item.getAttribute(attrID, m_settings.getUnitsType());

                final HTMLTable.ICell headercell = header.newCell();
                headercell.setText(attr.getName(), true);

                if (attr != null) {
                    boolean fail = (m_metrics[attrID] > 0) && !attr.passes(item, m_metrics[attrID]);

                    buf.setLength(0);
                    attr.format(item, buf);

                    final HTMLTable.ICell cell = coverage.newCell();
                    cell.setText(buf.toString(), true);
                    if (fail)
                        cell.setClass(CSS_DATA_HIGHLIGHT);
                }
            }
        }
        page.add(summaryTable);

        // [all] stats summary table ([all] only):

        page.addH(2, "OVERALL STATS SUMMARY", null);

        final HTMLTable statsTable = new HTMLTable(null, null, null, "0");
        statsTable.setClass(CSS_INVISIBLE_TABLE);
        {
            HTMLTable.IRow row = statsTable.newRow();
            row.newCell().setText("total packages:", true);
            row.newCell().setText("" + item.getChildCount(), false);

            if (m_srcView && m_hasSrcFileInfo) {
                row = statsTable.newRow();
                row.newCell().setText("total executable files:", true);
                row.newCell().setText("" + item.getAggregate(IItem.TOTAL_SRCFILE_COUNT), false);
            }

            row = statsTable.newRow();
            row.newCell().setText("total classes:", true);
            row.newCell().setText("" + item.getAggregate(IItem.TOTAL_CLASS_COUNT), true);
            row = statsTable.newRow();
            row.newCell().setText("total methods:", true);
            row.newCell().setText("" + item.getAggregate(IItem.TOTAL_METHOD_COUNT), true);

            if (m_srcView && m_hasSrcFileInfo && m_hasLineNumberInfo) {
                row = statsTable.newRow();
                row.newCell().setText("total executable lines:", true);
                row.newCell().setText("" + item.getAggregate(IItem.TOTAL_LINE_COUNT), true);
            }
        }
        /*
        {
        final HTMLTable.IRow first = statsTable.newRow (); // stats always available
                
        first.newCell ().setText ("total packages: " + item.getChildCount (), true);
        first.newCell ().setText ("total classes: " + item.getAggregate (IItem.TOTAL_CLASS_COUNT), true);
        first.newCell ().setText ("total methods: " + item.getAggregate (IItem.TOTAL_METHOD_COUNT), true);
                
        if (m_srcView && m_hasSrcFileInfo)
        {
            final HTMLTable.IRow second = statsTable.newRow ();
                    
            final HTMLTable.ICell cell1 = second.newCell ();
            cell1.setText ("total source files: " + item.getAggregate (IItem.TOTAL_SRCFILE_COUNT), true);
                
            if (m_hasLineNumberInfo)
            {
                final HTMLTable.ICell cell2 = second.newCell ();
                        
                cell2.setText ("total executable source lines: " + item.getAggregate (IItem.TOTAL_LINE_COUNT), true);
                cell2.getAttributes ().set (Attribute.COLSPAN, "2");
            }
            else
            {
                cell1.getAttributes ().set (Attribute.COLSPAN, "3");
            }
        }
        }
        */
        page.add(statsTable);

        final boolean deeper = (m_settings.getDepth() > item.getMetadata().getTypeID());

        // render package summary tables on the same page:

        page.addH(2, "COVERAGE BREAKDOWN BY PACKAGE", null);

        final HTMLTable childSummaryTable = new HTMLTable("100%", null, null, "0");
        {
            int[] headerColumns = null;

            boolean odd = true;
            final ItemComparator order = m_typeSortComparators[PackageItem.getTypeMetadata().getTypeID()];
            for (Iterator packages = item.getChildren(order); packages.hasNext(); odd = !odd) {
                final IItem pkg = (IItem) packages.next();

                if (headerColumns == null) {
                    // header row:
                    headerColumns = addHeaderRow(pkg, childSummaryTable, columns);
                }

                // coverage row:
                String childHREF = null;
                if (deeper) {
                    childHREF = getItemHREF(item, pkg);
                }
                addItemRow(pkg, odd, childSummaryTable, headerColumns, childHREF, false);

                if (deeper)
                    m_queue.addLast(pkg);
            }
        }
        page.add(childSummaryTable);

        page.emit(out);
        out.flush();
    } finally {
        if (out != null)
            out.close();
        out = null;
    }

    return ctx;
}