Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

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

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java

/**
 * @inheritDoc/*from   ww w .ja va  2  s  .  c  o  m*/
 */
public boolean getTagComboExists(List tags, Weblog weblog) throws WebloggerException {

    if (tags == null || tags.size() == 0) {
        return false;
    }

    StringBuffer queryString = new StringBuffer();
    queryString.append("SELECT DISTINCT w.name ");
    queryString.append("FROM WeblogEntryTagAggregate w WHERE w.name IN (");
    //?1) AND w.weblog = ?2");
    //Append tags as parameter markers to avoid potential escaping issues
    //The IN clause would be of form (?1, ?2, ?3, ..)
    ArrayList params = new ArrayList(tags.size() + 1);
    final String PARAM_SEPERATOR = ", ";
    int i;
    for (i = 0; i < tags.size(); i++) {
        queryString.append('?').append(i + 1).append(PARAM_SEPERATOR);
        params.add(tags.get(i));
    }

    // Remove the trailing PARAM_SEPERATOR
    queryString.delete(queryString.length() - PARAM_SEPERATOR.length(), queryString.length());
    // Close the brace of IN clause
    queryString.append(')');

    if (weblog != null) {
        queryString.append(" AND w.weblog = ?").append(i + 1);
        params.add(weblog);
    } else {
        queryString.append(" AND w.weblog IS NULL");
    }

    Query q = strategy.getDynamicQuery(queryString.toString());
    for (int j = 0; j < params.size(); j++) {
        q.setParameter(j + 1, params.get(j));
    }
    List results = q.getResultList();

    //TODO: DatamapperPort: Since we are only interested in knowing whether
    //results.size() == tags.size(). This query can be optimized to just fetch COUNT
    //instead of objects as done currently
    return (results != null && results.size() == tags.size());
}

From source file:de.interactive_instruments.ShapeChange.Target.SQL.SqlDdl.java

/**
 * @param tableName//from  ww  w . ja  v  a 2s.  c  o m
 *            - does not need to be normalized
 * @param pi
 */
private void generateCheckConstraintForEnumerationValueType(String tableName, PropertyInfo pi) {

    /*
     * ignore the constraint if the enumeration which is the value type of
     * pi is mapped to a simple type (example: usage of the 'Boolean' type
     * from ISO 19103).
     */
    ProcessMapEntry pme = this.mapEntryByType.get(pi.typeInfo().name);

    if (pme != null && !pme.hasParam()) {
        return;
    }

    // look up the enumeration type
    ClassInfo enumCi = model.classById(pi.typeInfo().id);

    if (enumCi == null || enumCi.properties().size() == 0) {

        result.addError(this, 18, pi.typeInfo().name, pi.fullNameInSchema());
    } else {

        StringBuffer sb2 = new StringBuffer();

        sb2.append("ALTER TABLE " + normalizeName(tableName) + " ADD CONSTRAINT "
                + createNameCheckConstraint(tableName, pi.name()) + " CHECK (" + normalizeName(pi.name())
                + " IN (");

        for (PropertyInfo enumPi : enumCi.properties().values()) {
            sb2.append("'" + StringUtils.replace(enumPi.name(), "'", "''") + "', "); // escape single quotes in the enumeration value
        }
        sb2.delete(sb2.length() - 2, sb2.length());
        sb2.append("));" + CRLF);

        if (!this.checkConstraintsForPropsWithEnumValueTypeByTableName.containsKey(tableName)) {

            this.checkConstraintsForPropsWithEnumValueTypeByTableName.put(tableName, new ArrayList<String>());
        }

        this.checkConstraintsForPropsWithEnumValueTypeByTableName.get(tableName).add(sb2.toString());

    }
}

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

/**
 * The main workhorse method./*from   w w w  .j  a v  a2  s.  com*/
 */
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:net.lightbody.bmp.proxy.jetty.util.URI.java

/** Convert a path to a cananonical form.
 * All instances of "." and ".." are factored out.  Null is returned
 * if the path tries to .. above it's root.
 * @param path //from  w  w  w  .j ava2 s  .  c o m
 * @return path or null.
 */
public static String canonicalPath(String path) {
    if (path == null || path.length() == 0)
        return path;

    int end = path.length();
    int queryIdx = path.indexOf('?');
    int start = path.lastIndexOf('/', (queryIdx > 0 ? queryIdx : end));

    search: while (end > 0) {
        switch (end - start) {
        case 2: // possible single dot
            if (path.charAt(start + 1) != '.')
                break;
            break search;
        case 3: // possible double dot
            if (path.charAt(start + 1) != '.' || path.charAt(start + 2) != '.')
                break;
            break search;
        }

        end = start;
        start = path.lastIndexOf('/', end - 1);
    }

    // If we have checked the entire string
    if (start >= end)
        return path;

    StringBuffer buf = new StringBuffer(path);
    int delStart = -1;
    int delEnd = -1;
    int skip = 0;

    while (end > 0) {
        switch (end - start) {
        case 2: // possible single dot
            if (buf.charAt(start + 1) != '.') {
                if (skip > 0 && --skip == 0) {
                    delStart = start >= 0 ? start : 0;
                    if (delStart > 0 && delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                        delStart++;
                }
                break;
            }

            if (start < 0 && buf.length() > 2 && buf.charAt(1) == '/' && buf.charAt(2) == '/')
                break;

            if (delEnd < 0)
                delEnd = end;
            delStart = start;
            if (delStart < 0 || delStart == 0 && buf.charAt(delStart) == '/') {
                delStart++;
                if (delEnd < buf.length() && buf.charAt(delEnd) == '/')
                    delEnd++;
                break;
            }
            if (end == buf.length())
                delStart++;

            end = start--;
            while (start >= 0 && buf.charAt(start) != '/')
                start--;
            continue;

        case 3: // possible double dot
            if (buf.charAt(start + 1) != '.' || buf.charAt(start + 2) != '.') {
                if (skip > 0 && --skip == 0) {
                    delStart = start >= 0 ? start : 0;
                    if (delStart > 0 && delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                        delStart++;
                }
                break;
            }

            delStart = start;
            if (delEnd < 0)
                delEnd = end;

            skip++;
            end = start--;
            while (start >= 0 && buf.charAt(start) != '/')
                start--;
            continue;

        default:
            if (skip > 0 && --skip == 0) {
                delStart = start >= 0 ? start : 0;
                if (delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                    delStart++;
            }
        }

        // Do the delete
        if (skip <= 0 && delStart >= 0 && delStart >= 0) {
            buf.delete(delStart, delEnd);
            delStart = delEnd = -1;
            if (skip > 0)
                delEnd = end;
        }

        end = start--;
        while (start >= 0 && buf.charAt(start) != '/')
            start--;
    }

    // Too many ..
    if (skip > 0)
        return null;

    // Do the delete
    if (delEnd >= 0)
        buf.delete(delStart, delEnd);

    return buf.toString();
}

From source file:org.gbif.portal.service.log.TripletQueryLoggingInterceptor.java

/**
 * Creates a brief message from the criteria
 * @param messagePreamble/*from w  ww . j a  va2  s .  c om*/
 * @param criteria
 * @return
 */
protected void createMessagePreamble(StringBuffer messagePreamble, List<PropertyStoreTripletDTO> criteria) {
    Map<String, Set<String>> subjects = new HashMap<String, Set<String>>();

    for (PropertyStoreTripletDTO dto : criteria) {
        String subject = dto.getSubject();
        String loggableSubject = getServiceKeyToBriefLoggableName().get(subject);

        // only log the ones we care about - e.g. ones we can make sense of
        if (loggableSubject != null) {
            String value = null;
            // some of them are null due to "coordinates areNot null" for example
            if (dto.getObject() != null) {
                value = dto.getObject().toString();
            }

            // map the object to what it really is - e.g. ID -> loggable string
            if (serviceObjectToLoggableStringMappers.containsKey(subject)) {
                LoggableFromPredicateAndObject converter = serviceObjectToLoggableStringMappers.get(subject);
                value = converter.getLoggable(dto.getPredicate(), dto.getObject());
                if (value == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Unable to get a loggable for key[" + dto.getObject() + "] using ["
                                + converter.getClass().getSimpleName() + "] - ignoring from message");
                    }
                }
            }

            if (value != null) {
                if (subjects.containsKey(loggableSubject)) {
                    subjects.get(loggableSubject).add(value);
                } else {
                    Set<String> values = new HashSet<String>();
                    values.add(value);
                    subjects.put(loggableSubject, values);
                }
            }
        }
    }

    for (String subject : subjects.keySet()) {
        messagePreamble.append(subject + "[");
        for (String value : subjects.get(subject)) {
            messagePreamble.append(value + ",");
        }
        messagePreamble.delete(messagePreamble.lastIndexOf(","), messagePreamble.lastIndexOf(",") + 1);
        messagePreamble.append("] ");
    }
}

From source file:com.mysql.stresstool.RunnableClusterQueryInsert.java

@Override
public boolean createSchema(StressTool sTool) {
    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;/* www.  java  2s  .  co m*/
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable + "(");
            if (this.isUseAutoIncrement()) {
                sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            }
            sb.append(" `a` int(11) NOT NULL,");
            sb.append(" `uuid` char(36) NOT NULL,");
            sb.append(" `b` varchar(100) NOT NULL,");
            sb.append(" `c` char(200)  NOT NULL,");
            sb.append(" `counter` bigint(20) NULL, ");
            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            sb.append(" `strrecordtype` char(3) NULL");
            if (this.isUseAutoIncrement()) {
                sb.append(", PRIMARY KEY  (`autoInc`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            } else {
                if (!this.doSimplePk)
                    sb.append(", PRIMARY KEY  (`uuid`),  INDEX `IDX_a` (a) ");
                else
                    sb.append(", PRIMARY KEY  (`a`),  INDEX `IDX_uuid` (uuid) ");
            }
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
            }

            for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                System.out.println("**** Please wait DROP table tbtest_child" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(DropTables2 + iTable);
            }

            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SharepointConnectorType.java

/**
 * Validates all the patterns under included / excluded to check if any of
 * them is not a valid pattern.//from  w w w  . j  a v a 2s  .com
 *
 * @param patterns
 *          The pattern to be validated
 * @return the set of wrong patterns, if any. Otherwise returns null
 */
private Set<String> validatePatterns(final String patterns) {
    LOGGER.info("validating patterns [ " + patterns + " ]. ");
    String[] patternsList = null;
    if ((patterns != null) && (patterns.trim().length() != 0)) {
        patternsList = patterns.split(SPConstants.SEPARATOR);
    }
    if (patternsList == null) {
        return null;
    }

    final Set<String> invalidPatterns = new HashSet<String>();

    for (final String pattern : patternsList) {
        if (pattern.startsWith(SPConstants.HASH) || pattern.startsWith(SPConstants.MINUS)) {
            continue;
        }
        if (pattern.startsWith(SPConstants.CONTAINS)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strContainKey = new String(tempBuffer.delete(0, SPConstants.CONTAINS.length()));
            try {
                new RE(strContainKey); // with case
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexPattrn = new String(tempBuffer.delete(0, SPConstants.REGEXP.length()));
            try {
                new RE(strRegexPattrn);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP_CASE)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexCasePattrn = new String(
                    tempBuffer.delete(0, SPConstants.REGEXP_CASE.length()));
            try {
                new RE(strRegexCasePattrn);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP_IGNORE_CASE)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexIgnoreCasePattrn = new String(
                    tempBuffer.delete(0, SPConstants.REGEXP_IGNORE_CASE.length()));
            try {
                new RE(strRegexIgnoreCasePattrn, RE.REG_ICASE); // ignore
                // case
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.CARET) || pattern.endsWith(SPConstants.DOLLAR)) {
            StringBuffer tempBuffer = new StringBuffer(pattern);
            boolean bDollar = false;
            if (pattern.startsWith(SPConstants.CARET)) {
                tempBuffer = new StringBuffer(pattern);
                final int indexOfStar = tempBuffer.indexOf("*");
                if (indexOfStar != -1) {
                    tempBuffer.replace(indexOfStar, indexOfStar + "*".length(), "[0-9].*");
                } else {
                    tempBuffer.delete(0, "^".length());
                    if (pattern.endsWith(SPConstants.DOLLAR)) {
                        bDollar = true;
                        tempBuffer.delete(tempBuffer.length() - SPConstants.DOLLAR.length(),
                                tempBuffer.length());
                    }
                    try {
                        final URL urlPatt = new URL(tempBuffer.toString());
                        final int port = urlPatt.getPort();
                        final String strHost = urlPatt.getHost().toString();
                        if ((port == -1) && (strHost != null) && (strHost.length() != 0)) {
                            tempBuffer = new StringBuffer("^" + urlPatt.getProtocol() + SPConstants.URL_SEP
                                    + urlPatt.getHost() + ":[0-9].*" + urlPatt.getPath());
                        }
                        if (bDollar) {
                            tempBuffer.append(SPConstants.DOLLAR);
                        }
                    } catch (final Exception e) {
                        tempBuffer = new StringBuffer(pattern);
                    }
                }
            }

            try {
                new RE(tempBuffer);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        String patternDecoded = pattern;
        try {
            patternDecoded = URLDecoder.decode(pattern, "UTF-8");
        } catch (final Exception e) {
            // eatup exception. use the original value
            patternDecoded = pattern;
        }

        if (patternDecoded == null) {
            invalidPatterns.add(pattern);
        }

        boolean containProtocol = false;
        try {
            final RE re = new RE(SPConstants.URL_SEP);
            final REMatch reMatch = re.getMatch(patternDecoded);
            if (reMatch != null) {
                containProtocol = true; // protocol is present
            }

        } catch (final Exception e) {
            containProtocol = false;
        }

        if (containProtocol) {
            String urlPatt1stPart = null;
            String urlPatt2ndPart = null;
            boolean bPortStar = false;
            try {
                final URL urlPatt = new URL(patternDecoded);
                final int port = urlPatt.getPort();
                String strPort = "";
                if (port == -1) {
                    strPort = "[0-9].*";
                } else {
                    strPort = port + "";
                }
                urlPatt1stPart = "^" + urlPatt.getProtocol() + SPConstants.URL_SEP + urlPatt.getHost()
                        + SPConstants.COLON + strPort;
                if (!(urlPatt.getFile()).startsWith(SPConstants.SLASH)) { // The pattern must have "/" 
                                                                          // after the port
                    invalidPatterns.add(pattern);
                }
                urlPatt2ndPart = "^" + urlPatt.getFile();
            } catch (final Exception e) {
                bPortStar = true;
            }

            if (bPortStar) {
                final int indexOfStar = patternDecoded.indexOf("*");
                if (indexOfStar != -1) {
                    urlPatt1stPart = "^" + patternDecoded.substring(0, indexOfStar) + "[0-9].*";
                    if (!(patternDecoded.substring(indexOfStar + 1)).startsWith(SPConstants.SLASH)) {
                        invalidPatterns.add(pattern);
                    }
                    urlPatt2ndPart = "^" + patternDecoded.substring(indexOfStar + 1);
                }
            }

            try {
                new RE(urlPatt1stPart);
                new RE(urlPatt2ndPart);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
        } else {
            String urlPatt1stPart = null;
            String urlPatt2ndPart = null;
            if (patternDecoded.indexOf(SPConstants.SLASH) != -1) {
                if (patternDecoded.indexOf(SPConstants.COLON) == -1) {
                    urlPatt1stPart = patternDecoded.substring(0, patternDecoded.indexOf(SPConstants.SLASH))
                            + ":[0-9].*";
                } else {
                    urlPatt1stPart = patternDecoded.substring(0, patternDecoded.indexOf(SPConstants.SLASH));
                }
                urlPatt2ndPart = patternDecoded.substring(patternDecoded.indexOf(SPConstants.SLASH));
            } else {
                invalidPatterns.add(pattern);
            }

            urlPatt1stPart = "^.*://.*" + urlPatt1stPart;
            urlPatt2ndPart = "^" + urlPatt2ndPart;
            try {
                new RE(urlPatt1stPart);
                new RE(urlPatt2ndPart);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
        }
    }
    if (invalidPatterns.size() == 0) {
        return null;
    } else {
        return invalidPatterns;
    }
}

From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java

@Override
public HashMap<ProfileRecipientFields, ValidatorResults> getDuplicateRecipientsFromNewDataOnly(
        Map<ProfileRecipientFields, ValidatorResults> listOfValidBeans, ImportProfile profile,
        CSVColumnState[] columns, Integer adminID, int datasource_id) {
    final HashMap<ProfileRecipientFields, ValidatorResults> result = new HashMap<ProfileRecipientFields, ValidatorResults>();
    if (listOfValidBeans.isEmpty()) {
        return result;
    }/*from   w  ww  .ja v  a2 s.co  m*/

    final String prefix = "cust_" + adminID + "_tmp_";
    final String tableName = prefix + datasource_id + "_tbl";
    final HashMap<ImportKeyColumnsKey, ProfileRecipientFields> columnKeyValueToTemporaryIdMap = new HashMap<ImportKeyColumnsKey, ProfileRecipientFields>();
    final JdbcTemplate template = getJdbcTemplateForTemporaryTable();
    List parameters = new ArrayList();
    Map<String, List<Object>> parametersMap = new HashMap<String, List<Object>>();
    String columnKeyBuffer = "(";
    for (ProfileRecipientFields profileRecipientFields : listOfValidBeans.keySet()) {
        ImportKeyColumnsKey keyValue = ImportKeyColumnsKey.createInstance(profile, profileRecipientFields,
                columns);
        if (columnKeyValueToTemporaryIdMap.containsKey(keyValue)) {
            result.put(profileRecipientFields, null);
            continue;
        }

        columnKeyBuffer += keyValue.getParametersString();
        keyValue.addParameters(parametersMap);

        columnKeyValueToTemporaryIdMap.put(keyValue, profileRecipientFields);
    }
    columnKeyBuffer = columnKeyBuffer.substring(0, columnKeyBuffer.length() - 1);
    columnKeyBuffer = columnKeyBuffer + ")";
    ImportKeyColumnsKey keyColumnsKey = columnKeyValueToTemporaryIdMap.keySet().iterator().next();
    Iterator<String> keyColumnIterator = keyColumnsKey.getKeyColumnsMap().keySet().iterator();
    StringBuffer sqlQuery = new StringBuffer("SELECT ");
    StringBuffer wherePart = new StringBuffer("");
    int index = 0;
    while (keyColumnIterator.hasNext()) {
        String keyColumnName = keyColumnIterator.next();
        CSVColumnState columnState = keyColumnsKey.getKeyColumnsMap().get(keyColumnName);
        String column = "i.column_duplicate_check_" + index;
        String columnAlias = ImportKeyColumnsKey.KEY_COLUMN_PREFIX + keyColumnName;
        sqlQuery.append(column + " AS " + columnAlias + ",");
        int type = columnState.getType();
        if (AgnUtils.isOracleDB() && (keyColumnName.equals("email") || type == CSVColumnState.TYPE_NUMERIC
                || type == CSVColumnState.TYPE_DATE)) {
            wherePart.append(column);
        } else {
            wherePart.append("LOWER(" + column + ")");
        }
        wherePart.append(" IN " + columnKeyBuffer + " AND ");
        // gather parameters
        List<Object> objectList = parametersMap.get(keyColumnName);
        if (objectList != null) {
            parameters.addAll(objectList);
        }
        index++;
    }

    sqlQuery.delete(sqlQuery.length() - 1, sqlQuery.length());
    sqlQuery.append(" FROM " + tableName + " i  WHERE (");
    sqlQuery.append(wherePart);
    sqlQuery.append("(i.status_type=" + NewImportWizardService.RECIPIENT_TYPE_VALID + " OR i.status_type="
            + NewImportWizardService.RECIPIENT_TYPE_FIXED_BY_HAND + " OR i.status_type="
            + NewImportWizardService.RECIPIENT_TYPE_DUPLICATE_RECIPIENT + "))");

    final List<Map> resultList = template.queryForList(sqlQuery.toString(), parameters.toArray());
    for (Map row : resultList) {
        ImportKeyColumnsKey columnsKey = ImportKeyColumnsKey.createInstance(row);
        ProfileRecipientFields recipientFields = columnKeyValueToTemporaryIdMap.get(columnsKey);
        if (recipientFields != null) {
            result.put(recipientFields, null);
        }
    }
    return result;
}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    IEngUserProfile profile;//w  w  w. java 2 s.co m
    JobDataMap jobDataMap;

    // documentLabel__num this is necessary because the same document can be added to one scheduled activity more than one time
    String documentInstanceName;
    String documentLabel;

    // par1=val1&par2=val2... for parameters already set in scheduled activity's configuration
    String inputParametersQueryString;

    IBIObjectDAO biobjdao;
    BIObject biobj;
    ExecutionController executionController;
    ExecutionProxy executionProxy;
    EventsManager eventManager;

    logger.debug("IN");

    try {
        profile = UserProfile.createSchedulerUserProfile();
        jobDataMap = jobExecutionContext.getMergedJobDataMap();
        biobjdao = DAOFactory.getBIObjectDAO();

        String doclabelsConcat = jobDataMap.getString("documentLabels");
        String[] docLabels = doclabelsConcat.split(",");
        Iterator itr = jobDataMap.keySet().iterator();
        while (itr.hasNext()) {
            Object key = itr.next();
            Object value = jobDataMap.get(key);
            logger.debug("jobDataMap parameter [" + key + "] is equal to [" + value + "]");
        }

        long startSchedule = System.currentTimeMillis();
        logger.debug("Scheduled activity contains [" + docLabels.length + "] documnt(s)");

        for (int ind = 0; ind < docLabels.length; ind++) {
            documentInstanceName = docLabels[ind];
            documentLabel = documentInstanceName.substring(0, documentInstanceName.lastIndexOf("__"));
            logger.debug("Processing document [" + (ind + 1) + "] with label [" + documentLabel + "] ...");

            inputParametersQueryString = jobDataMap.getString(documentInstanceName);
            logger.debug("Input parameters query string for documet [" + documentLabel + "] is equal to ["
                    + inputParametersQueryString + "]");

            // load bidocument
            biobj = biobjdao.loadBIObjectByLabel(documentLabel);

            // get the save options
            String saveOptString = jobDataMap.getString("biobject_id_" + biobj.getId() + "__" + (ind + 1));
            DispatchContext saveInfo = SchedulerUtilities.decodeDispatchContext(saveOptString);

            // create the execution controller 
            executionController = new ExecutionController();
            executionController.setBiObject(biobj);

            // fill parameters 
            executionController.refreshParameters(biobj, inputParametersQueryString);

            String iterativeParametersString = jobDataMap.getString(documentInstanceName + "_iterative");
            logger.debug("Iterative parameter configuration for documet [" + documentLabel + "] is equal to ["
                    + iterativeParametersString + "]");
            setIterativeParameters(biobj, iterativeParametersString);

            String loadAtRuntimeParametersString = jobDataMap
                    .getString(documentInstanceName + "_loadAtRuntime");
            logger.debug("Runtime parameter configuration for documet [" + documentLabel + "] is equal to ["
                    + loadAtRuntimeParametersString + "]");
            setLoadAtRuntimeParameters(biobj, loadAtRuntimeParametersString);

            String useFormulaParametersString = jobDataMap.getString(documentInstanceName + "_useFormula");
            logger.debug("Formuula based parameter configuration for documet [" + documentLabel
                    + "] is equal to [" + useFormulaParametersString + "]");
            setUseFormulaParameters(biobj, useFormulaParametersString);

            retrieveParametersValues(biobj);

            //gets the dataset data about the email address
            IDataStore emailDispatchDataStore = null;
            if (saveInfo.isUseDataSet()) {
                IDataSet dataSet = DAOFactory.getDataSetDAO()
                        .loadActiveDataSetByLabel(saveInfo.getDataSetLabel());
                dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes(profile));
                dataSet.loadData();
                emailDispatchDataStore = dataSet.getDataStore();
            }
            //gets the dataset data about the folder for the document save
            IDataStore folderDispatchDataSotre = null;
            if (saveInfo.isUseFolderDataSet()) {
                IDataSet dataSet = DAOFactory.getDataSetDAO()
                        .loadActiveDataSetByLabel(saveInfo.getDataSetFolderLabel());
                dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes(profile));
                dataSet.loadData();
                folderDispatchDataSotre = dataSet.getDataStore();
            }

            eventManager = EventsManager.getInstance();
            List roles = DAOFactory.getBIObjectDAO().getCorrectRolesForExecution(biobj.getId());

            String startExecMsg = "${scheduler.startexecsched} " + biobj.getName();
            Integer idEvent = eventManager.registerEvent("Scheduler", startExecMsg, "", roles);

            Map tempParMap = new HashMap();
            BIObjectParametersIterator objectParametersIterator = new BIObjectParametersIterator(
                    biobj.getBiObjectParameters());
            while (objectParametersIterator.hasNext()) {
                List parameters = (List) objectParametersIterator.next();
                biobj.setBiObjectParameters(parameters);

                StringBuffer toBeAppendedToName = new StringBuffer();
                StringBuffer toBeAppendedToDescription = new StringBuffer(" [");
                Iterator parametersIt = parameters.iterator();
                while (parametersIt.hasNext()) {

                    BIObjectParameter aParameter = (BIObjectParameter) parametersIt.next();

                    tempParMap.put(aParameter.getParameterUrlName(), aParameter.getParameterValuesAsString());
                    if (aParameter.isIterative()) {
                        toBeAppendedToName.append("_" + aParameter.getParameterValuesAsString());
                        toBeAppendedToDescription.append(
                                aParameter.getLabel() + ":" + aParameter.getParameterValuesAsString() + "; ");
                    }
                }
                // if there are no iterative parameters, toBeAppendedToDescription is " [" and must be cleaned
                if (toBeAppendedToDescription.length() == 2) {
                    toBeAppendedToDescription.delete(0, 2);
                } else {
                    // toBeAppendedToDescription ends with "; " and must be cleaned
                    toBeAppendedToDescription.delete(toBeAppendedToDescription.length() - 2,
                            toBeAppendedToDescription.length());
                    toBeAppendedToDescription.append("]");
                }

                // appending the current date
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat();
                sdf.applyPattern("dd:MM:yyyy");
                String dateStr = sdf.format(date);
                toBeAppendedToName.append("_" + dateStr);

                //check parameters value: if a parameter hasn't value but isn't mandatory the process 
                //must go on and so hasValidValue is set to true
                List tmpBIObjectParameters = biobj.getBiObjectParameters();
                Iterator it = tmpBIObjectParameters.iterator();
                while (it.hasNext()) {
                    boolean isMandatory = false;
                    BIObjectParameter aBIObjectParameter = (BIObjectParameter) it.next();
                    List checks = aBIObjectParameter.getParameter().getChecks();
                    if (checks != null && !checks.isEmpty()) {
                        Iterator checksIt = checks.iterator();
                        while (checksIt.hasNext()) {
                            Check check = (Check) checksIt.next();
                            if (check.getValueTypeCd().equalsIgnoreCase("MANDATORY")) {
                                isMandatory = true;
                                break;
                            }
                        }
                    }
                    if (!isMandatory && (aBIObjectParameter.getParameterValues() == null
                            || aBIObjectParameter.getParameterValues().size() == 0)) {
                        aBIObjectParameter.setParameterValues(new ArrayList());
                        aBIObjectParameter.setHasValidValues(true);
                    }
                }

                // exec the document only if all its parameter are filled
                if (executionController.directExecution()) {

                    logger.debug("Save as snapshot is eual to [" + saveInfo.isSnapshootDispatchChannelEnabled()
                            + "]");
                    logger.debug("Dispatch to a distribution list is eual to ["
                            + saveInfo.isDistributionListDispatchChannelEnabled() + "]");
                    logger.debug("Dispatch to a java class is eual to ["
                            + saveInfo.isJavaClassDispatchChannelEnabled() + "]");
                    logger.debug("Dispatch by mail-list is eual to [" + saveInfo.isMailDispatchChannelEnabled()
                            + "]");
                    logger.debug("Dispatch by folder-list is eual to ["
                            + saveInfo.isFunctionalityTreeDispatchChannelEnabled() + "]");

                    if (!saveInfo.isSnapshootDispatchChannelEnabled()
                            && !saveInfo.isDistributionListDispatchChannelEnabled()
                            && !saveInfo.isJavaClassDispatchChannelEnabled()) {
                        boolean noValidDispatchTarget = false;
                        if (saveInfo.isMailDispatchChannelEnabled()) {
                            String[] recipients = findRecipients(saveInfo, biobj, emailDispatchDataStore);
                            if (recipients != null && recipients.length > 0) {
                                noValidDispatchTarget = false;
                                logger.debug("Found at least one target of type mail");
                            } else {
                                noValidDispatchTarget = true;
                            }
                        }

                        if (saveInfo.isFunctionalityTreeDispatchChannelEnabled()) {
                            List storeInFunctionalities = findFolders(saveInfo, biobj, folderDispatchDataSotre);
                            if (storeInFunctionalities != null && !storeInFunctionalities.isEmpty()) {
                                noValidDispatchTarget = false;
                                logger.debug("Found at least one target of type folder");
                            } else {
                                noValidDispatchTarget = true;
                            }
                        }

                        if (noValidDispatchTarget) {
                            logger.debug("No valid dispatch target for document [" + (ind + 1)
                                    + "] with label [" + documentInstanceName + "] and parameters ["
                                    + toBeAppendedToDescription + "]");
                            logger.info("Document [" + (ind + 1) + "] with label [" + documentInstanceName
                                    + "] and parameters " + toBeAppendedToDescription
                                    + " not executed: no valid dispatch target");
                            continue;
                        } else if (!saveInfo.isFunctionalityTreeDispatchChannelEnabled()
                                && !saveInfo.isMailDispatchChannelEnabled()) {
                            logger.debug("There are no dispatch targets for document with label ["
                                    + documentInstanceName
                                    + "] - if not an ETL, WEKA or KPI document a dispatch target should be added");
                        } else {
                            logger.debug("There is at list one dispatch target for document with label ["
                                    + documentInstanceName + "]");
                        }
                    }

                    executionProxy = new ExecutionProxy();
                    executionProxy.setBiObject(biobj);

                    logger.info("Executing document [" + (ind + 1) + "] with label [" + documentInstanceName
                            + "] and parameters " + toBeAppendedToDescription + " ...");
                    long start = System.currentTimeMillis();
                    byte[] response = executionProxy.exec(profile, "SCHEDULATION", null);
                    if (response == null || response.length == 0) {
                        logger.debug("Document executed without any response");
                    }
                    String retCT = executionProxy.getReturnedContentType();
                    String fileextension = executionProxy.getFileExtensionFromContType(retCT);
                    long end = System.currentTimeMillis();
                    long elapsed = (end - start) / 1000;
                    logger.info("Document [" + (ind + 1) + "] with label [" + documentInstanceName
                            + "] and parameters " + toBeAppendedToDescription + " executed in [" + elapsed
                            + "]");

                    if (saveInfo.isSnapshootDispatchChannelEnabled()) {
                        saveAsSnap(saveInfo, biobj, response, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString(), profile);
                    }

                    if (saveInfo.isFunctionalityTreeDispatchChannelEnabled()) {
                        saveAsDocument(saveInfo, biobj, jobExecutionContext, response, fileextension,
                                folderDispatchDataSotre, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                    }

                    if (saveInfo.isMailDispatchChannelEnabled()) {
                        sendMail(saveInfo, biobj, tempParMap, response, retCT, fileextension,
                                emailDispatchDataStore, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                    }
                    if (saveInfo.isDistributionListDispatchChannelEnabled()) {
                        sendToDl(saveInfo, biobj, response, retCT, fileextension, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                        if (jobExecutionContext.getNextFireTime() == null) {
                            String triggername = jobExecutionContext.getTrigger().getName();
                            List dlIds = saveInfo.getDlIds();
                            it = dlIds.iterator();
                            while (it.hasNext()) {
                                Integer dlId = (Integer) it.next();
                                DistributionList dl = DAOFactory.getDistributionListDAO()
                                        .loadDistributionListById(dlId);
                                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                                        (biobj.getId()).intValue(), triggername);
                            }
                        }
                    }

                    if (saveInfo.isJavaClassDispatchChannelEnabled()) {
                        sendToJavaClass(saveInfo, biobj, response);
                    }

                } else {
                    logger.warn("The document with label " + documentInstanceName
                            + " cannot be executed directly, " + "maybe some prameters are not filled ");
                    throw new Exception("The document with label " + documentInstanceName
                            + " cannot be executed directly, " + "maybe some prameters are not filled ");
                }
            }

            String endExecMsg = "${scheduler.endexecsched} " + biobj.getName();
            eventManager.registerEvent("Scheduler", endExecMsg, "", roles);

        }

        long endSchedule = System.currentTimeMillis();
        long elapsedSchedule = (endSchedule - startSchedule) / 1000;
        logger.info("Scheduled activity succesfully ended in [" + elapsedSchedule + "] sec.");
    } catch (Exception e) {
        logger.error("Error while executiong job ", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:com.mysql.stresstool.RunnableQueryInsert.java

@Override
public boolean createSchema(StressTool sTool) {

    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;/*  w ww  .java2s  .c  o  m*/
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable + "(");
            if (this.isUseAutoIncrement()) {
                sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            }
            sb.append(" `a` int(11) NOT NULL,");
            sb.append(" `uuid` char(36) NOT NULL,");
            sb.append(" `b` varchar(100) NOT NULL,");
            sb.append(" `c` char(200)  NOT NULL,");
            sb.append(" `counter` bigint(20) NULL, ");
            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            sb.append(" `strrecordtype` char(3) NULL");
            if (this.isUseAutoIncrement()) {
                sb.append(", PRIMARY KEY  (`autoInc`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            } else {
                if (!this.doSimplePk)
                    sb.append(", PRIMARY KEY  (`uuid`),  INDEX `IDX_a` (a) ");
                else
                    sb.append(", PRIMARY KEY  (`a`),  INDEX `IDX_uuid` (uuid) ");
            }
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait DROP table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(DropTables2 + iTable);
                }

            }
            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}