Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

In this page you can find the example usage for java.util LinkedHashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.datatorrent.stram.plan.physical.PhysicalPlan.java

private void redoPartitions(PMapping currentMapping, String note) {
    Partitioner<Operator> partitioner = getPartitioner(currentMapping);
    if (partitioner == null) {
        LOG.warn("No partitioner for {}", currentMapping.logicalOperator);
        return;/*from  w  w w  .  j a  va 2  s  .co  m*/
    }

    RepartitionContext mainPC = new RepartitionContext(partitioner, currentMapping, 0);
    if (mainPC.newPartitions.isEmpty()) {
        LOG.warn("Empty partition list after repartition: {}", currentMapping.logicalOperator);
        return;
    }

    int memoryPerPartition = currentMapping.logicalOperator.getValue(OperatorContext.MEMORY_MB);
    for (Map.Entry<OutputPortMeta, StreamMeta> stream : currentMapping.logicalOperator.getOutputStreams()
            .entrySet()) {
        if (stream.getValue().getLocality() != Locality.THREAD_LOCAL
                && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) {
            memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB);
        }
    }
    for (OperatorMeta pp : currentMapping.parallelPartitions) {
        for (Map.Entry<OutputPortMeta, StreamMeta> stream : pp.getOutputStreams().entrySet()) {
            if (stream.getValue().getLocality() != Locality.THREAD_LOCAL
                    && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) {
                memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB);
            }
        }
        memoryPerPartition += pp.getValue(OperatorContext.MEMORY_MB);
    }
    int requiredMemoryMB = (mainPC.newPartitions.size() - mainPC.currentPartitions.size()) * memoryPerPartition;
    if (requiredMemoryMB > availableMemoryMB) {
        LOG.warn("Insufficient headroom for repartitioning: available {}m required {}m", availableMemoryMB,
                requiredMemoryMB);
        return;
    }

    List<Partition<Operator>> addedPartitions = new ArrayList<Partition<Operator>>();
    // determine modifications of partition set, identify affected operator instance(s)
    for (Partition<Operator> newPartition : mainPC.newPartitions) {
        PTOperator op = mainPC.currentPartitionMap.remove(newPartition);
        if (op == null) {
            addedPartitions.add(newPartition);
        } else {
            // check whether mapping was changed
            for (DefaultPartition<Operator> pi : mainPC.currentPartitions) {
                if (pi == newPartition && pi.isModified()) {
                    // existing partition changed (operator or partition keys)
                    // remove/add to update subscribers and state
                    mainPC.currentPartitionMap.put(newPartition, op);
                    addedPartitions.add(newPartition);
                }
            }
        }
    }

    // remaining entries represent deprecated partitions
    this.undeployOpers.addAll(mainPC.currentPartitionMap.values());
    // downstream dependencies require redeploy, resolve prior to modifying plan
    Set<PTOperator> deps = this.getDependents(mainPC.currentPartitionMap.values());
    this.undeployOpers.addAll(deps);
    // dependencies need redeploy, except operators excluded in remove
    this.deployOpers.addAll(deps);

    // process parallel partitions before removing operators from the plan
    LinkedHashMap<PMapping, RepartitionContext> partitionContexts = Maps.newLinkedHashMap();
    Stack<OperatorMeta> parallelPartitions = new Stack<LogicalPlan.OperatorMeta>();
    parallelPartitions.addAll(currentMapping.parallelPartitions);
    pendingLoop: while (!parallelPartitions.isEmpty()) {
        OperatorMeta ppMeta = parallelPartitions.pop();
        for (StreamMeta s : ppMeta.getInputStreams().values()) {
            if (currentMapping.parallelPartitions.contains(s.getSource().getOperatorMeta())
                    && parallelPartitions.contains(s.getSource().getOperatorMeta())) {
                parallelPartitions.push(ppMeta);
                parallelPartitions.remove(s.getSource().getOperatorMeta());
                parallelPartitions.push(s.getSource().getOperatorMeta());
                continue pendingLoop;
            }
        }
        LOG.debug("Processing parallel partition {}", ppMeta);

        PMapping ppm = this.logicalToPTOperator.get(ppMeta);
        Partitioner<Operator> ppp = getPartitioner(ppm);
        if (ppp == null) {
            partitionContexts.put(ppm, null);
        } else {
            RepartitionContext pc = new RepartitionContext(ppp, ppm, mainPC.newPartitions.size());
            if (pc.newPartitions == null) {
                throw new IllegalStateException(
                        "Partitioner returns null for parallel partition " + ppm.logicalOperator);
            }
            partitionContexts.put(ppm, pc);
        }
    }

    // plan updates start here, after all changes were identified
    // remove obsolete operators first, any freed resources
    // can subsequently be used for new/modified partitions
    List<PTOperator> copyPartitions = Lists.newArrayList(currentMapping.partitions);
    // remove deprecated partitions from plan
    for (PTOperator p : mainPC.currentPartitionMap.values()) {
        copyPartitions.remove(p);
        removePartition(p, currentMapping);
        mainPC.operatorIdToPartition.remove(p.getId());
    }
    currentMapping.partitions = copyPartitions;

    // add new operators
    for (Partition<Operator> newPartition : addedPartitions) {
        PTOperator p = addPTOperator(currentMapping, newPartition, mainPC.minCheckpoint);
        mainPC.operatorIdToPartition.put(p.getId(), newPartition);
    }

    // process parallel partition changes
    for (Map.Entry<PMapping, RepartitionContext> e : partitionContexts.entrySet()) {
        if (e.getValue() == null) {
            // no partitioner, add required operators
            for (int i = 0; i < addedPartitions.size(); i++) {
                LOG.debug("Automatically adding to parallel partition {}", e.getKey());
                // set activation windowId to confirm to upstream checkpoints
                addPTOperator(e.getKey(), null, mainPC.minCheckpoint);
            }
        } else {
            RepartitionContext pc = e.getValue();
            // track previous parallel partition mapping
            Map<Partition<Operator>, Partition<Operator>> prevMapping = Maps.newHashMap();
            for (int i = 0; i < mainPC.currentPartitions.size(); i++) {
                prevMapping.put(pc.currentPartitions.get(i), mainPC.currentPartitions.get(i));
            }
            // determine which new partitions match upstream, remaining to be treated as new operator
            Map<Partition<Operator>, Partition<Operator>> newMapping = Maps.newHashMap();
            Iterator<Partition<Operator>> itMain = mainPC.newPartitions.iterator();
            Iterator<Partition<Operator>> itParallel = pc.newPartitions.iterator();
            while (itMain.hasNext() && itParallel.hasNext()) {
                newMapping.put(itParallel.next(), itMain.next());
            }

            for (Partition<Operator> newPartition : pc.newPartitions) {
                PTOperator op = pc.currentPartitionMap.remove(newPartition);
                if (op == null) {
                    pc.addedPartitions.add(newPartition);
                } else if (prevMapping.get(newPartition) != newMapping.get(newPartition)) {
                    // upstream partitions don't match, remove/add to replace with new operator
                    pc.currentPartitionMap.put(newPartition, op);
                    pc.addedPartitions.add(newPartition);
                } else {
                    // check whether mapping was changed - based on DefaultPartition implementation
                    for (DefaultPartition<Operator> pi : pc.currentPartitions) {
                        if (pi == newPartition && pi.isModified()) {
                            // existing partition changed (operator or partition keys)
                            // remove/add to update subscribers and state
                            mainPC.currentPartitionMap.put(newPartition, op);
                            pc.addedPartitions.add(newPartition);
                        }
                    }
                }
            }

            if (!pc.currentPartitionMap.isEmpty()) {
                // remove obsolete partitions
                List<PTOperator> cowPartitions = Lists.newArrayList(e.getKey().partitions);
                for (PTOperator p : pc.currentPartitionMap.values()) {
                    cowPartitions.remove(p);
                    removePartition(p, e.getKey());
                    pc.operatorIdToPartition.remove(p.getId());
                }
                e.getKey().partitions = cowPartitions;
            }
            // add new partitions
            for (Partition<Operator> newPartition : pc.addedPartitions) {
                PTOperator oper = addPTOperator(e.getKey(), newPartition, mainPC.minCheckpoint);
                pc.operatorIdToPartition.put(oper.getId(), newPartition);
            }

            getPartitioner(e.getKey()).partitioned(pc.operatorIdToPartition);
        }
    }

    updateStreamMappings(currentMapping);
    for (PMapping pp : partitionContexts.keySet()) {
        updateStreamMappings(pp);
    }

    deployChanges();

    if (mainPC.currentPartitions.size() != mainPC.newPartitions.size()) {
        StramEvent ev = new StramEvent.PartitionEvent(currentMapping.logicalOperator.getName(),
                mainPC.currentPartitions.size(), mainPC.newPartitions.size());
        ev.setReason(note);
        this.ctx.recordEventAsync(ev);
    }

    partitioner.partitioned(mainPC.operatorIdToPartition);
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static void insertPixAclIntoDB(LinkedHashMap lmap, int device_id) {
    Connection c = null;/*from w  w  w. j a  v a  2 s  .com*/
    PreparedStatement ps = null;

    try {
        try {
            DBHelper.executeUpdate("delete from device_acl_table where device_id=" + device_id);
        } catch (Exception ee) {
            logger.warn("Error while deleting from device_acl_table", device_id, ee);
        }

        c = DBHelper.getConnection();
        c.setAutoCommit(false);

        Iterator it = lmap.keySet().iterator();
        // ps = c.prepareStatement(DBHelperConstants.INSERT_PIX_ACL_DATA);
        ps = c.prepareStatement(DBHelperConstants.INSERT_ACL_DATA);

        // System.out.println("Inside insertPixAclIntoDB\t" +
        // lmap.toString());
        while (it.hasNext()) {
            String aclId = (String) it.next();
            ArrayList alist = (ArrayList) lmap.get(aclId);
            Iterator itr = alist.iterator();
            while (itr.hasNext()) {
                PixAccessListElement pelem = (PixAccessListElement) itr.next();
                // device_id, aclId, aceData, aclData, matches
                ps.setInt(1, device_id);
                ps.setString(2, aclId);
                ps.setString(3, pelem.getAceData());
                ps.setString(4, pelem.getAclData());
                ps.setString(5, pelem.getMatches());
                try {
                    ps.executeUpdate();
                } catch (Exception e) {
                    logger.warn(
                            "Exception while inserting pix aclid\t" + aclId + "\t for \t" + pelem.getAclData());
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Exception while inserting Pix ACLS into DB.", e);
    } finally {
        try {
            ps.close();
        } catch (Exception ee) {
        }

        try {
            c.commit();
        } catch (Exception e1) {
        }

        try {
            c.setAutoCommit(true);
        } catch (Exception ee) {
        }
        DBHelper.releaseConnection(c);
    }
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Processes changes to persistent collection that contains instances of OpenmrsObject objects.
 * <p>//from   ww w  . j a  v a2s.  c  om
 * Remarks:
 * <p>
 * Xml 'schema' for the sync item content for the persisted collection follows. Note that for persisted
 * collections syncItemKey is a composite of owner object uuid and the property name that contains the
 * collection. <br/>
 * &lt;persistent-collection&gt; element: wrapper element <br/>
 * &lt;owner uuid='' propertyName='' type='' action='recreate|update' &gt; element: this
 * captures the information about the object that holds reference to the collection being
 * processed <br/>
 * -uuid: owner object uuid <br/>
 * -properyName: names of the property on owner object that holds this collection <br/>
 * -type: owner class name <br/>
 * -action: recreate, update -- these are collection events defined by hibernate interceptor <br/>
 * &lt;entry action='update|delete' uuid='' type='' &gt; element: this captures info about
 * individual collection entries: <br/>
 * -action: what is being done to this item of the collection: delete (item was removed from the
 * collection) or update (item was added to the collection) <br/>
 * -uuid: entry's uuid <br/>
 * -type: class name
 *
 * @param collection Instance of Hibernate AbstractPersistentCollection to process.
 * @param key key of owner for the collection.
 * @param action action being performed on the collection: update, recreate
 */
private void processPersistentCollection(AbstractPersistentCollection collection, Serializable key,
        String action, String originalRecordUuid, OpenmrsObject owner, String ownerPropertyName) {

    LinkedHashMap<String, OpenmrsObject> entriesHolder = null;

    // Setup the serialization data structures to hold the state
    Package pkg = new Package();
    entriesHolder = new LinkedHashMap<String, OpenmrsObject>();
    try {

        CollectionMetadata collMD = getCollectionMetadata(owner.getClass(), ownerPropertyName,
                getSessionFactory());
        if (collMD == null) {
            throw new SyncException(
                    "Can't find a collection with " + ownerPropertyName + " in class " + owner.getClass());
        }

        Class<?> elementClass = collMD.getElementType().getReturnedClass();
        //If this is a simple type like Integer, serialization of the collection will be as below:
        //<org.openmrs.Cohort>
        //   <memberIds type="java.util.Set(org.openmrs.Cohort)">[2, 3]</memberIds>
        //  ............. and more
        //This should work just fine as long as there is a Normalizer registered for it
        if (!OpenmrsObject.class.isAssignableFrom(elementClass)
                && SyncUtil.getNormalizer(elementClass) != null) {

            //Check if there is already a NEW/UPDATE sync item for the owner
            SyncItem syncItem = new SyncItem();
            syncItem.setKey(new SyncItemKey<String>(owner.getUuid(), String.class));
            syncItem.setContainedType(owner.getClass());
            syncItem.setState(SyncItemState.UPDATED);

            boolean ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);
            syncItem.setState(SyncItemState.NEW);
            if (!ownerHasSyncItem)
                ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);

            if (!ownerHasSyncItem) {
                ClassMetadata cmd = getSessionFactory().getClassMetadata(owner.getClass());
                //create an UPDATE sync item for the owner so that the collection changes get recorded along
                Serializable primaryKeyValue = cmd.getIdentifier(owner,
                        (SessionImplementor) getSessionFactory().getCurrentSession());
                packageObject(owner, cmd.getPropertyValues(owner, EntityMode.POJO), cmd.getPropertyNames(),
                        cmd.getPropertyTypes(), primaryKeyValue, SyncItemState.UPDATED);
            } else {
                //There is already an UPDATE OR NEW SyncItem for the owner containing the above updates
            }

            return;
        }
        // find out what entries need to be serialized
        for (Object entry : (Iterable) collection) {
            if (entry instanceof OpenmrsObject) {
                OpenmrsObject obj = (OpenmrsObject) entry;

                // attempt to retrieve entry uuid
                String entryUuid = obj.getUuid();
                if (entryUuid == null) {
                    entryUuid = fetchUuid(obj);
                    if (log.isDebugEnabled()) {
                        log.debug("Entry uuid was null, attempted to fetch uuid with the following results");
                        log.debug("Entry type:" + obj.getClass().getName() + ",uuid:" + entryUuid);
                    }
                }
                // well, this is messed up: have an instance of
                // OpenmrsObject but has no uuid
                if (entryUuid == null) {
                    log.error("Cannot handle collection entries where uuid is null.");
                    throw new CallbackException("Cannot handle collection entries where uuid is null.");
                }

                // add it to the holder to avoid possible duplicates: key =
                // uuid + action
                entriesHolder.put(entryUuid + "|update", obj);
            } else {
                log.warn(
                        "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers. Type was "
                                + entry.getClass() + " in property " + ownerPropertyName + " in class "
                                + owner.getClass());
                // skip out early because we don't want to write any xml for it
                // it was handled by the normal property writer hopefully
                return;
            }
        }

        // add on deletes
        if (!"recreate".equals(action) && collection.getRole() != null) {
            org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory())
                    .getCollectionPersister(collection.getRole());
            Iterator it = collection.getDeletes(persister, false);
            if (it != null) {
                while (it.hasNext()) {
                    Object entryDelete = it.next();
                    if (entryDelete instanceof OpenmrsObject) {
                        OpenmrsObject objDelete = (OpenmrsObject) entryDelete;
                        // attempt to retrieve entry uuid
                        String entryDeleteUuid = objDelete.getUuid();
                        if (entryDeleteUuid == null) {
                            entryDeleteUuid = fetchUuid(objDelete);
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "Entry uuid was null, attempted to fetch uuid with the following results");
                                log.debug("Entry type:" + entryDeleteUuid.getClass().getName() + ",uuid:"
                                        + entryDeleteUuid);
                            }
                        }
                        // well, this is messed up: have an instance of
                        // OpenmrsObject but has no uuid
                        if (entryDeleteUuid == null) {
                            log.error("Cannot handle collection delete entries where uuid is null.");
                            throw new CallbackException(
                                    "Cannot handle collection delete entries where uuid is null.");
                        }

                        // add it to the holder to avoid possible
                        // duplicates: key = uuid + action
                        // also, only add if there is no update action for the same object: see SYNC-280
                        if (!entriesHolder.containsKey(entryDeleteUuid + "|update")) {
                            entriesHolder.put(entryDeleteUuid + "|delete", objDelete);
                        }

                    } else {
                        // TODO: more debug info
                        log.warn(
                                "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers!");
                        // skip out early because we don't want to write any
                        // xml for it. it
                        // was handled by the normal property writer
                        // hopefully
                        return;
                    }
                }
            }
        }

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal. note: when making SyncItemKey, make it a composite
         * string of uuid + prop. name to avoid collisions with updates to
         * parent object or updates to more than one collection on same
         * owner
         */

        // Setup the serialization data structures to hold the state
        Record xml = pkg.createRecordForWrite(collection.getClass().getName());
        Item entityItem = xml.getRootItem();

        // serialize owner info: we will need type, prop name where collection
        // goes, and owner uuid
        Item item = xml.createItem(entityItem, "owner");
        item.setAttribute("type", this.getType(owner));
        item.setAttribute("properyName", ownerPropertyName);
        item.setAttribute("action", action);
        item.setAttribute("uuid", owner.getUuid());

        // build out the xml for the item content
        Boolean hasNoAutomaticPrimaryKey = null;
        String type = null;
        for (String entryKey : entriesHolder.keySet()) {
            OpenmrsObject entryObject = entriesHolder.get(entryKey);
            if (type == null) {
                type = this.getType(entryObject);
                hasNoAutomaticPrimaryKey = SyncUtil.hasNoAutomaticPrimaryKey(type);
            }

            Item temp = xml.createItem(entityItem, "entry");
            temp.setAttribute("type", type);
            temp.setAttribute("action", entryKey.substring(entryKey.indexOf('|') + 1));
            temp.setAttribute("uuid", entryObject.getUuid());
            if (hasNoAutomaticPrimaryKey) {
                temp.setAttribute("primaryKey", getSyncService().getPrimaryKey(entryObject));
            }
        }

        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(owner.getUuid() + "|" + ownerPropertyName, String.class));
        syncItem.setState(SyncItemState.UPDATED);
        syncItem.setContainedType(collection.getClass());
        syncItem.setContent(xml.toStringAsDocumentFragment());

        getSyncRecord().addOrRemoveAndAddItem(syncItem);
        getSyncRecord().addContainedClass(owner.getClass().getName());

        // do the original uuid dance, same as in packageObject
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (Exception ex) {
        log.error("Error processing Persistent collection, see callstack and inner expection", ex);
        throw new CallbackException(
                "Error processing Persistent collection, see callstack and inner expection.", ex);
    }
}

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

public static ASTNode genSelectDIAST(RowResolver rr) {
    LinkedHashMap<String, LinkedHashMap<String, ColumnInfo>> map = rr.getRslvMap();
    ASTNode selectDI = new ASTNode(new CommonToken(HiveParser.TOK_SELECTDI, "TOK_SELECTDI"));
    // Note: this will determine the order of columns in the result. For now, the columns for each
    //       table will be together; the order of the tables, as well as the columns within each
    //       table, is deterministic, but undefined - RR stores them in the order of addition.
    for (String tabAlias : map.keySet()) {
        for (Entry<String, ColumnInfo> entry : map.get(tabAlias).entrySet()) {
            selectDI.addChild(buildSelExprSubTree(tabAlias, entry.getKey()));
        }/*www.j a  v  a 2s  .  com*/
    }
    return selectDI;
}

From source file:com.primeleaf.krystal.web.view.console.ViewDocumentView.java

@SuppressWarnings("unchecked")
private void printDocument() throws Exception {
    Document document = (Document) request.getAttribute("DOCUMENT");
    DocumentRevision documentRevision = (DocumentRevision) request.getAttribute("DOCUMENTREVISION");
    DocumentClass documentClass = (DocumentClass) request.getAttribute("DOCUMENTCLASS");

    LinkedHashMap<String, String> documentIndexes = (LinkedHashMap<String, String>) request
            .getAttribute("DOCUMENTINDEXES");
    boolean isHeadRevision = document.getRevisionId().equalsIgnoreCase(documentRevision.getRevisionId());

    ACL acl = (ACL) request.getAttribute("ACL");

    if (view.trim().length() <= 0) {//do not show document id and revision id for attachment or quick view
        printBreadCrumbs();/*  w w  w.  j a  va 2s . c o m*/
    }

    out.println("<h3><i class=\"fa fa-folder-open\"></i> "
            + StringEscapeUtils.escapeHtml4(documentClass.getClassName()));
    out.println("<small>");
    out.println(
            "<span class=\"label label-success tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Document ID\">"
                    + documentRevision.getDocumentId() + "</span>&nbsp;");
    out.println(
            "<span class=\"label label-default tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Revision ID\">"
                    + documentRevision.getRevisionId() + "</span>&nbsp;");
    out.println(
            "<span class=\"label label-success tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"File Size\">"
                    + StringHelper.formatSizeText(documentRevision.getLength()) + "</span></small></h3>");

    String lastModified = "";
    if (document.getModified() == null) {
        lastModified = document.getCreated();
    } else {
        lastModified = document.getModified().toString();
    }
    out.println("Last Modified By &nbsp;" + StringEscapeUtils.escapeHtml4(document.getModifiedBy()));
    out.println("&nbsp;");
    out.println("On &nbsp;" + StringHelper.formatDate(lastModified));
    out.println(" (" + StringHelper.getFriendlyDateTime(lastModified) + ")");

    out.println("<hr/>");

    if (request.getAttribute(HTTPConstants.REQUEST_ERROR) != null) {
        printErrorDismissable((String) request.getAttribute(HTTPConstants.REQUEST_ERROR));
    }
    if (request.getAttribute(HTTPConstants.REQUEST_MESSAGE) != null) {
        printSuccessDismissable((String) request.getAttribute(HTTPConstants.REQUEST_MESSAGE));
    }

    out.println("<ul class=\"nav nav-tabs\" id=\"documenTabs\">");
    out.println("<li class=\"active\"><a href=\"#document\" data-toggle=\"tab\"><img src=\"/images/"
            + StringHelper.getIconFileNameForExtension(document.getExtension())
            + ".gif\" >&nbsp;Document</a></li>");
    out.println(
            "<li><a href=\"#documentNotes\" data-toggle=\"tab\" class=\"internal\"  datatarget=\"#resultNotes\" data-src=\"/console/documentnotes?documentid="
                    + document.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                    + "\"><i class=\"fa fa-comments-o\"></i> Notes</a></li>");
    out.println(
            "<li><a href=\"#accessHistory\" data-toggle=\"tab\" class=\"internal\"  datatarget=\"#resultAccessHistory\" data-src=\"/console/accesshistory?documentid="
                    + document.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                    + "\"><i class=\"fa fa-clock-o\"></i> Access History</a></li>");
    out.println("</ul>");
    out.println("<div class=\"tab-content\">");
    out.println("<div class=\"tab-pane in active\" id=\"document\"><br/>");
    out.println("<div class=\"row\">");
    out.println("<div class=\"col-sm-9\">");
    //viewer applet starts here
    try {

        out.println("<div class=\"well well-sm\" id=\"viewer\">");
        out.println("<iframe src = \"/js/ViewerJS/?type=pdf#/console/mobiledocumentviewer?documentid="
                + documentRevision.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                + "\" width='100%' height='800'></iframe>");
        out.println("</div>");//visible-xs

        if (acl.canEmail()) {
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\"><i class=\"fa fa-envelope-o\"></i> Share Document</div>");
            out.println("<div class=\"panel-body\">");
            out.println(
                    "<form action=\"/console/sharedocument\" method=\"post\" id=\"frmShareDocument\" form-type=\"ajax\" datatarget=\"#resultShareDocument\">");
            out.println("<div id=\"resultShareDocument\"></div>");
            out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");

            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtEmail\">Email ID <span style='color:red'>*</span></label>");
            out.println(
                    "<input type=\"text\" id=\"txtEmail\" name=\"txtEmail\" class=\"required form-control multiemail\" maxlength=\"500\" title=\"Please use a comma to separate multiple email addresses\"/>");
            out.println("</div>");

            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtComments\">Comments <span style='color:red'>*</span></label>");
            out.println(
                    "<textarea class=\"form-control required\" rows=\"4\" name=\"txtComments\"  id=\"txtComments\"  placeholder=\"Put your comments here\"></textarea>");
            out.println("</div>");
            out.println("<input type=\"hidden\"  name=\"documentid\"     value=\"" + document.getDocumentId()
                    + "\" />");
            out.println("<input type=\"hidden\"  name=\"revisionid\"     value=\""
                    + documentRevision.getRevisionId() + "\" />");
            out.println(
                    "<input type=\"submit\"  name=\"btnSubmit\"    id=\"btnShare\"    value=\"Share Document\"    class=\"btn btn-sm btn-default\"  data-loading-text=\"Sharing Document...\"/>");
            out.println("</form>");
            out.println("</div>");//panel-body
            out.println("</div>");//panel
        }

        out.println("</div>");//col-sm-9

        out.println("<div class=\"col-sm-3\">");
        String expiryOn = "";
        if (document.getExpiry() == null) {
            expiryOn = "";
        } else {
            expiryOn = document.getExpiry().toString();
            expiryOn = StringHelper.formatDate(expiryOn, ServerConstants.FORMAT_SHORT_DATE);
        }
        String lastAccessed = "";
        if (document.getLastAccessed() == null) {
            lastAccessed = document.getCreated();
        } else {
            lastAccessed = document.getLastAccessed().toString();
        }

        if (acl.canWrite() && document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE) && isHeadRevision) {
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\"><i class=\"fa fa-list\"></i> Edit Indexes</div>");
            out.println("<div class=\"panel-body\">");
            out.println(
                    "<form action=\"/console/editdocumentindexes\" method=\"post\" id=\"frmEditIndexes\" accept-charset=\"utf-8\"  form-type=\"ajax\" datatarget=\"#resultIndexes\">");
            out.println("<div id=\"resultIndexes\"></div>");
            out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                String required = "";
                out.println("<div class=\"form-group\">");
                out.println("<label for=\"" + indexDefinition.getIndexColumnName() + "\"> "
                        + StringEscapeUtils.escapeHtml4(indexDefinition.getIndexDisplayName()));
                if (indexDefinition.isMandatory()) {
                    required = "required";
                    out.println(" <span style='color:red'>*</span>");
                }
                out.println("</label>");

                String value = (String) documentIndexes.get(indexDefinition.getIndexDisplayName());
                value = StringEscapeUtils.escapeHtml4(value);

                if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_DATE)) {
                    out.println("<div class=\"input-group\">");
                    out.println("<input type=\"text\" class=\"shortdate isdate form-control " + required
                            + "\" name=\"" + indexDefinition.getIndexColumnName() + "\" id=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                    out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
                    out.println("</div>");
                } else if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_NUMBER)) {
                    out.println("<input type=\"text\" class=\"number  form-control " + required
                            + " autocomplete\"    id=\"" + indexDefinition.getIndexColumnName() + "\" name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"   cid=\"" + documentClass.getClassId()
                            + "\">");
                } else {
                    out.println("<input type=\"text\" class=\"autocomplete form-control " + required
                            + " \" id=\"" + indexDefinition.getIndexColumnName() + "\"  name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                }
                out.println("</div>");
            }

            out.println("<hr/>");
            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtExpiryDate\"> Expiry On</label>");
            out.println("<div class=\"input-group\">");
            out.println(
                    "<input type=\"text\" class=\"shortdate isdate form-control\" name=\"txtExpiryDate\" id=\"txtExpiryDate\" maxlength=\"12\" value=\""
                            + expiryOn + "\"/>");
            out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
            out.println("</div>");
            out.println("</div>");

            out.println("<input type=\"hidden\" name=\"revisionid\" value=\"" + documentRevision.getRevisionId()
                    + "\">");
            out.println("<input type=\"hidden\"  name=\"documentid\"  value=\"" + document.getDocumentId()
                    + "\"/>");
            out.println(
                    "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");

            out.println("</form>");
            out.println("</div>");//panel-body
            out.println("</div>");//panel

        } else {
            out.println("<div class=\"panel panel-default\">");
            out.println(
                    "<div class=\"panel-heading\"><i class=\"fa fa-check-square-o\"></i> Document Indexes</div>");
            out.println("<div class=\"panel-body\">");
            out.println("<div class=\"table-responsive\">");
            out.println("<table class=\"table table-hover\">");
            if (!documentIndexes.keySet().isEmpty()) {
                out.println("<thead>");
                out.println("<tr>");
                out.println("<th>Index Field</th>");
                out.println("<th>Index Value</th>");
                out.println("</tr>");
                out.println("</thead>");

                out.println("<tbody>");
                for (String indexName : documentIndexes.keySet()) {
                    String indexValue = (String) documentIndexes.get(indexName);
                    out.println("<tr>");
                    out.println("<td>" + StringEscapeUtils.escapeHtml4(indexName) + "</td>");
                    out.println("<td>" + StringEscapeUtils.escapeHtml4(indexValue) + "</td>");
                    out.println("</tr>");
                }
            }
            out.println("<tr class=\"text-success\">");
            out.println("<td >Expiry On</td>");
            out.println("<td>" + expiryOn + "</td>");
            out.println("</tr>");

            out.println("</tbody>");
            out.println("</table>");
            out.println("</div>");//table-responsive
            out.println("</div>");//panel-body
            out.println("</div>");//panel
        }

        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-file\"></i> Document Properties</div>");
        out.println("<div class=\"table-responsive\">");
        out.println("<table class=\"table table-hover\">");
        out.println("<thead><tr><th>Property</th><th>Value</th></tr></thead>");
        out.println("<tbody><tr><td>Created By</td><td> " + document.getCreatedBy() + "</td></tr>");
        out.println("<tr><td>Created On</td><td>" + StringHelper.getFriendlyDateTime(document.getCreated())
                + "</td></tr>");
        out.println("<tr><td>Last Accessed On</td><td>" + StringHelper.getFriendlyDateTime(lastAccessed)
                + "</td></tr>");
        out.println("<tr><td>Access Count</td><td>" + document.getAccessCount() + "</td></tr>");
        out.println("</tbody></table>");//
        out.println("</div>");//table-responsive
        out.println("</div>");//panel

        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-bookmark\"></i> Bookmark Document</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/newbookmark\" method=\"post\" id=\"frmNewBookmark\"  form-type=\"ajax\" datatarget=\"#resultBookmark\" accept-charset=\"utf-8\">");
        out.println("<div id=\"resultBookmark\"></div>");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"txtBookmarkName\">Bookmark Name<span style='color:red'>*</span></label>");
        out.println(
                "<input type=\"text\" id=\"txtBookmarkName\" name=\"txtBookmarkName\" class=\"required form-control\" maxlength=\"50\" title=\"Please enter Bookmark Name\"/>");
        out.println("</div>");
        out.println("<input type=\"hidden\"  name=\"documentid\"     value=\"" + document.getDocumentId()
                + "\" />");
        out.println("<input type=\"hidden\"  name=\"revisionid\"     value=\""
                + documentRevision.getRevisionId() + "\" />");
        out.println("<input type=\"submit\"  name=\"btnSubmit\"     value=\"" + "Save"
                + "\"    class=\"btn btn-sm btn-default\"/>");
        out.println("</form>");
        out.println("</div>");//panel-body
        out.println("</div>");//panel

        if (view.trim().length() <= 0) {
            out.println("<div class=\"well well-sm\">");
            if (acl.canDownload()) {
                out.println("<a href=\"/console/downloaddocument?documentid=" + document.getDocumentId()
                        + "&revisionid=" + documentRevision.getRevisionId()
                        + "\" class=\"btn btn-default btn-block \" title=\"Download Document\" ><i class=\"fa fa-download\"></i> Download Document</a>");
            }
            if (documentClass.isRevisionControlEnabled()) {
                if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE) && isHeadRevision) {
                    if (acl.canCheckout()) {
                        out.println("<a href=\"/console/checkoutdocument?documentid=" + document.getDocumentId()
                                + "\" class=\"btn btn-default btn-block \" title=\"Check Out Document\" ><i class=\"fa fa-lock\"></i> Check Out Document</a>");
                    }
                }
                if (document.getStatus().equalsIgnoreCase(Hit.STATUS_LOCKED)) {
                    out.println("<a href=\"/console/cancelcheckout?documentid=" + document.getDocumentId()
                            + "\" class=\"btn  btn-default btn-block confirm\" title=\"Are you sure, you want to cancel checkout of this document?\" ><i class=\"fa fa-unlock-alt\"></i> Cancel Checkout</a>");
                    if (acl.canCheckin()) {
                        out.println("<a href=\"/console/checkindocument?documentid=" + document.getDocumentId()
                                + "\" class=\"btn  btn-default btn-block \" title=\"Check In\" ><i class=\"fa fa-arrow-right\"></i> Check In</a>");
                    }
                }
                out.println("<a href=\"/console/revisionhistory?documentid=" + document.getDocumentId()
                        + "\" data-toggle=\"modal\" data-target=\"#revisionHistoryModal\" class=\"btn  btn-default btn-block \" title=\"Revision History\"><i class=\"fa fa-clock-o\"></i> Revision History</a>");
            }
            if (acl.canDelete() && document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)
                    && isHeadRevision) {
                out.println("<a href=\"/console/deletedocument?documentid=" + document.getDocumentId()
                        + "\" class=\"btn btn-danger btn-block confirm\" title=\"Are you sure, you want to mark this document as deleted?\" ><i class=\"fa fa-trash-o\"></i> Delete Document</a>");
            }
            out.println("</div>");//well well-sm
        }
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//tab-pane active #document

        out.println("<div class=\"tab-pane fade\" id=\"attachment\">");
        out.println(
                "<iframe frameborder=\"0\" border=\"0\" width=\"0\" height=\"0\" name=\"attachmentFrame\" id=\"attachmentFrame\" src=\"\" style=\"border:0px;\"></iframe>");

        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultAttachments\"></div>");
        out.println("</div>");//col-sm-9

        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-paperclip\"></i> Add Attachment</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/attachments\" method=\"post\" id=\"frmAttachments\" name=\"frmAttachments\" enctype=\"multipart/form-data\" target=\"attachmentFrame\" accept-charset=\"utf-8\" class=\"internal\">");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"fileDocument\">Select Document <span style='color:red'>*</span></label>");
        out.println(
                "<input type=\"file\" name=\"fileDocument\" class=\"required\" title=\"Please select document\">");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"TITLE\">Attachment Title <span class=\"text-success\">*</span></label>");
        out.println(
                "<input type=\"text\" name=\"TITLE\" id=\"TITLE\" class=\"form-control required\" title=\"Please enter attachment title\" placeholder=\"Attachment Title\"/>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"KEYWORDS\">Attachment Keywords </label>");
        out.println(
                "<textarea name=\"KEYWORDS\" id=\"KEYWORDS\" rows=\"5\" class=\"form-control\" placeholder=\"Attachment Keywords\"></textarea>");
        out.println("</div>");

        out.println("<div class=\"form-group\" id=\"pbContainer\" style=\"display:none;\">");
        out.println("<div class=\"progress progress-striped active\" id=\"progressbarMain\">");
        out.println(
                "<div class=\"progress-bar progress-bar-success\" id=\"progressbar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 0%\">");
        out.println("<span class=\"sr-only\">0% Complete</span>");
        out.println("</div>");
        out.println("</div>");
        out.println(
                "<div id=\"progressMessage\" class=\"alert alert-success alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button></div>");
        out.println("</div>");

        out.println("<input type=\"hidden\" name=\"DOCID\" value=\"" + document.getDocumentId() + "\">");
        out.println("<input type=\"hidden\" name=\"REVISIONID\" value=\"" + documentRevision.getRevisionId()
                + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");
        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//panel-body
        out.println("</div>");//panel
        out.println("</div>");//tab-pane active #attachment

        out.println("<div class=\"tab-pane fade\" id=\"documentNotes\"><br/>");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultNotes\"></div>");//notes will be loaded here
        out.println("</div>");//col-sm-9
        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println(
                "<div class=\"panel-heading\"><i class=\"fa fa-comment-o fa-lg\"></i> Add Note / Comments</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/documentnotes\" id=\"frmNotes\" method=\"post\"  form-type=\"ajax\" datatarget=\"#resultNotes\">");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"txtNote\">Note / Comments <span class=\"text-success\">*</span></label>");
        out.println(
                "<textarea name=\"txtNote\" id=\"txtNote\" rows=\"5\" class=\"form-control required alphaNumericSpace\" title=\"Please enter note\" placeholder=\"Note / Comments\"></textarea>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<div class=\"btn-group\" data-toggle=\"buttons\">");
        out.println("<label class=\"btn btn-sm btn-default active\">");
        out.println(
                "<input type=\"radio\" id=\"radNoteType1\" name=\"radNoteType\" value=\"P\" checked>Public");
        out.println("</label>");
        out.println("<label class=\"btn btn-sm btn-default\">");
        out.println("<input type=\"radio\" id=\"radNoteType2\" name=\"radNoteType\"  value=\"U\">Private");
        out.println("</label>");
        out.println("</div>");
        out.println("</div>");

        out.println("<hr/>");
        out.println("<input type=\"hidden\" name=\"documentid\" value=\"" + document.getDocumentId() + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");

        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row

        out.println("</div>");//panel-body
        out.println("</div>");//panel
        out.println("</div>");//tab-pane active #notes

        out.println("<div class=\"tab-pane fade\" id=\"accessHistory\"><br/>");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultAccessHistory\"></div>");//access history will be loaded here
        out.println("</div>");//col-sm-9
        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println(
                "<div class=\"panel-heading\"><i class=\"fa fa-filter fa-lg\"></i> Filter Access History</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/accesshistory\" id=\"frmAccessHistory\" method=\"post\" form-type=\"ajax\" datatarget=\"#resultAccessHistory\">");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"fromDate\">From</label>");
        out.println("<div class=\"input-group\">");
        out.println(
                "<input type=\"text\"  id=\"fromDate\" name=\"fromDate\" class=\"form-control shortdate isDate\">");
        out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
        out.println("</div>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"toDate\">To</label>");
        out.println("<div class=\"input-group\">");
        out.println(
                "<input type=\"text\"  id=\"toDate\" name=\"toDate\" class=\" form-control shortdate isDate\">");
        out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
        out.println("</div>");
        out.println("</div>");

        out.println("<input type=\"hidden\" name=\"documentid\" value=\"" + document.getDocumentId() + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Show Access History\" class=\"btn btn-sm btn-default btn-block\">");

        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//panel-body
        out.println("</div>");//panel

        out.println("</div>");//tab-pane active #accessHistory

        printModal("revisionHistoryModal");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    out.println("</div>");//tab-content
}

From source file:kreidos.diamond.web.view.console.ViewDocumentView.java

@SuppressWarnings("unchecked")
private void printDocument() throws Exception {
    Document document = (Document) request.getAttribute("DOCUMENT");
    DocumentRevision documentRevision = (DocumentRevision) request.getAttribute("DOCUMENTREVISION");
    DocumentClass documentClass = (DocumentClass) request.getAttribute("DOCUMENTCLASS");

    LinkedHashMap<String, String> documentIndexes = (LinkedHashMap<String, String>) request
            .getAttribute("DOCUMENTINDEXES");
    boolean isHeadRevision = document.getRevisionId().equalsIgnoreCase(documentRevision.getRevisionId());

    ACL acl = (ACL) request.getAttribute("ACL");

    if (view.trim().length() <= 0) {//do not show document id and revision id for attachment or quick view
        printBreadCrumbs();/*ww w . j a v a  2s. c  om*/
    }

    out.println("<h3><i class=\"fa fa-folder-open\"></i> "
            + StringEscapeUtils.escapeHtml4(documentClass.getClassName()));
    out.println("<small>");
    out.println(
            "<span class=\"label label-success tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Document ID\">"
                    + documentRevision.getDocumentId() + "</span>&nbsp;");
    out.println(
            "<span class=\"label label-default tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Revision ID\">"
                    + documentRevision.getRevisionId() + "</span>&nbsp;");
    out.println(
            "<span class=\"label label-success tip\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"File Size\">"
                    + StringHelper.formatSizeText(documentRevision.getLength()) + "</span></small></h3>");

    String lastModified = "";
    if (document.getModified() == null) {
        lastModified = document.getCreated();
    } else {
        lastModified = document.getModified().toString();
    }
    out.println("Last Modified By &nbsp;" + StringEscapeUtils.escapeHtml4(document.getModifiedBy()));
    out.println("&nbsp;");
    out.println("On &nbsp;" + StringHelper.formatDate(lastModified));
    out.println(" (" + StringHelper.getFriendlyDateTime(lastModified) + ")");

    out.println("<hr/>");

    if (request.getAttribute(HTTPConstants.REQUEST_ERROR) != null) {
        printErrorDismissable((String) request.getAttribute(HTTPConstants.REQUEST_ERROR));
    }
    if (request.getAttribute(HTTPConstants.REQUEST_MESSAGE) != null) {
        printSuccessDismissable((String) request.getAttribute(HTTPConstants.REQUEST_MESSAGE));
    }

    out.println("<ul class=\"nav nav-tabs\" id=\"documenTabs\">");
    out.println("<li class=\"active\"><a href=\"#document\" data-toggle=\"tab\"><img src=\"/images/"
            + StringHelper.getIconFileNameForExtension(document.getExtension())
            + ".gif\" >&nbsp;Document</a></li>");
    out.println(
            "<li><a href=\"#documentNotes\" data-toggle=\"tab\" class=\"internal\"  datatarget=\"#resultNotes\" data-src=\"/console/documentnotes?documentid="
                    + document.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                    + "\"><i class=\"fa fa-comments-o\"></i> Notes</a></li>");
    out.println(
            "<li><a href=\"#accessHistory\" data-toggle=\"tab\" class=\"internal\"  datatarget=\"#resultAccessHistory\" data-src=\"/console/accesshistory?documentid="
                    + document.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                    + "\"><i class=\"fa fa-clock-o\"></i> Access History</a></li>");
    out.println("</ul>");
    out.println("<div class=\"tab-content\">");
    out.println("<div class=\"tab-pane in active\" id=\"document\"><br/>");
    out.println("<div class=\"row\">");
    out.println("<div class=\"col-sm-9\">");
    //viewer applet starts here
    try {

        out.println("<div class=\"well well-sm\" id=\"viewer\">");
        out.println("<iframe src = \"/js/ViewerJS/?type=pdf#/console/mobiledocumentviewer?documentid="
                + documentRevision.getDocumentId() + "&revisionid=" + documentRevision.getRevisionId()
                + "\" width='100%' height='800'></iframe>");
        out.println("</div>");//visible-xs

        if (acl.canEmail()) {
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\"><i class=\"fa fa-envelope-o\"></i> Share Document</div>");
            out.println("<div class=\"panel-body\">");
            out.println(
                    "<form action=\"/console/sharedocument\" method=\"post\" id=\"frmShareDocument\" form-type=\"ajax\" datatarget=\"#resultShareDocument\">");
            out.println("<div id=\"resultShareDocument\"></div>");
            out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");

            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtEmail\">Email ID <span style='color:red'>*</span></label>");
            out.println(
                    "<input type=\"text\" id=\"txtEmail\" name=\"txtEmail\" class=\"required form-control multiemail\" maxlength=\"500\" title=\"Please use a comma to separate multiple email addresses\"/>");
            out.println("</div>");

            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtComments\">Comments <span style='color:red'>*</span></label>");
            out.println(
                    "<textarea class=\"form-control required\" rows=\"4\" name=\"txtComments\"  id=\"txtComments\"  placeholder=\"Put your comments here\"></textarea>");
            out.println("</div>");
            out.println("<input type=\"hidden\"  name=\"documentid\"     value=\"" + document.getDocumentId()
                    + "\" />");
            out.println("<input type=\"hidden\"  name=\"revisionid\"     value=\""
                    + documentRevision.getRevisionId() + "\" />");
            out.println(
                    "<input type=\"submit\"  name=\"btnSubmit\"    id=\"btnShare\"    value=\"Share Document\"    class=\"btn btn-sm btn-default\"  data-loading-text=\"Sharing Document...\"/>");
            out.println("</form>");
            out.println("</div>");//panel-body
            out.println("</div>");//panel
        }

        out.println("</div>");//col-sm-9

        out.println("<div class=\"col-sm-3\">");
        String expiryOn = "";
        if (document.getExpiry() == null) {
            expiryOn = "";
        } else {
            expiryOn = document.getExpiry().toString();
            expiryOn = StringHelper.formatDate(expiryOn, ServerConstants.FORMAT_SHORT_DATE);
        }
        String lastAccessed = "";
        if (document.getLastAccessed() == null) {
            lastAccessed = document.getCreated();
        } else {
            lastAccessed = document.getLastAccessed().toString();
        }

        if (acl.canWrite() && document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE) && isHeadRevision) {
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\"><i class=\"fa fa-list\"></i> Edit Indexes</div>");
            out.println("<div class=\"panel-body\">");
            out.println(
                    "<form action=\"/console/editdocumentindexes\" method=\"post\" id=\"frmEditIndexes\" accept-charset=\"utf-8\"  form-type=\"ajax\" datatarget=\"#resultIndexes\">");
            out.println("<div id=\"resultIndexes\"></div>");
            out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                String required = "";
                out.println("<div class=\"form-group\">");
                out.println("<label for=\"" + indexDefinition.getIndexColumnName() + "\"> "
                        + StringEscapeUtils.escapeHtml4(indexDefinition.getIndexDisplayName()));
                if (indexDefinition.isMandatory()) {
                    required = "required";
                    out.println(" <span style='color:red'>*</span>");
                }
                out.println("</label>");

                String value = (String) documentIndexes.get(indexDefinition.getIndexDisplayName());
                value = StringEscapeUtils.escapeHtml4(value);

                if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_DATE)) {
                    out.println("<div class=\"input-group\">");
                    out.println("<input type=\"text\" class=\"shortdate isdate form-control " + required
                            + "\" name=\"" + indexDefinition.getIndexColumnName() + "\" id=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                    out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
                    out.println("</div>");
                } else if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_NUMBER)) {
                    out.println("<input type=\"text\" class=\"number  form-control " + required
                            + " autocomplete\"    id=\"" + indexDefinition.getIndexColumnName() + "\" name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"   cid=\"" + documentClass.getClassId()
                            + "\">");
                } else {
                    out.println("<input type=\"text\" class=\"autocomplete form-control " + required
                            + " \" id=\"" + indexDefinition.getIndexColumnName() + "\"  name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                }
                out.println("</div>");
            }

            out.println("<hr/>");
            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtExpiryDate\"> Expiry On</label>");
            out.println("<div class=\"input-group\">");
            out.println(
                    "<input type=\"text\" class=\"shortdate isdate form-control\" name=\"txtExpiryDate\" id=\"txtExpiryDate\" maxlength=\"12\" value=\""
                            + expiryOn + "\"/>");
            out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
            out.println("</div>");
            out.println("</div>");

            out.println("<input type=\"hidden\" name=\"revisionid\" value=\"" + documentRevision.getRevisionId()
                    + "\">");
            out.println("<input type=\"hidden\"  name=\"documentid\"  value=\"" + document.getDocumentId()
                    + "\"/>");
            out.println(
                    "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");

            out.println("</form>");
            out.println("</div>");//panel-body
            out.println("</div>");//panel

        } else {
            out.println("<div class=\"panel panel-default\">");
            out.println(
                    "<div class=\"panel-heading\"><i class=\"fa fa-check-square-o\"></i> Document Indexes</div>");
            out.println("<div class=\"panel-body\">");
            out.println("<div class=\"table-responsive\">");
            out.println("<table class=\"table table-hover\">");
            if (!documentIndexes.keySet().isEmpty()) {
                out.println("<thead>");
                out.println("<tr>");
                out.println("<th>Index Field</th>");
                out.println("<th>Index Value</th>");
                out.println("</tr>");
                out.println("</thead>");

                out.println("<tbody>");
                for (String indexName : documentIndexes.keySet()) {
                    String indexValue = (String) documentIndexes.get(indexName);
                    out.println("<tr>");
                    out.println("<td>" + StringEscapeUtils.escapeHtml4(indexName) + "</td>");
                    out.println("<td>" + StringEscapeUtils.escapeHtml4(indexValue) + "</td>");
                    out.println("</tr>");
                }
            }
            out.println("<tr class=\"text-success\">");
            out.println("<td >Expiry On</td>");
            out.println("<td>" + expiryOn + "</td>");
            out.println("</tr>");

            out.println("</tbody>");
            out.println("</table>");
            out.println("</div>");//table-responsive
            out.println("</div>");//panel-body
            out.println("</div>");//panel
        }

        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-file\"></i> Document Properties</div>");
        out.println("<div class=\"table-responsive\">");
        out.println("<table class=\"table table-hover\">");
        out.println("<thead><tr><th>Property</th><th>Value</th></tr></thead>");
        out.println("<tbody>");
        if (document.getFilename() != null) //Show filename if present
            out.println("<tr><td>Filename</td><td> " + document.getFullFilename() + "</td></tr>");
        out.println("<tr><td>Created By</td><td> " + document.getCreatedBy() + "</td></tr>");
        out.println("<tr><td>Created On</td><td>" + StringHelper.getFriendlyDateTime(document.getCreated())
                + "</td></tr>");
        out.println("<tr><td>Last Accessed On</td><td>" + StringHelper.getFriendlyDateTime(lastAccessed)
                + "</td></tr>");
        out.println("<tr><td>Access Count</td><td>" + document.getAccessCount() + "</td></tr>");
        out.println("</tbody></table>");//
        out.println("</div>");//table-responsive
        out.println("</div>");//panel

        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-bookmark\"></i> Bookmark Document</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/newbookmark\" method=\"post\" id=\"frmNewBookmark\"  form-type=\"ajax\" datatarget=\"#resultBookmark\" accept-charset=\"utf-8\">");
        out.println("<div id=\"resultBookmark\"></div>");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"txtBookmarkName\">Bookmark Name<span style='color:red'>*</span></label>");
        out.println(
                "<input type=\"text\" id=\"txtBookmarkName\" name=\"txtBookmarkName\" class=\"required form-control\" maxlength=\"50\" title=\"Please enter Bookmark Name\"/>");
        out.println("</div>");
        out.println("<input type=\"hidden\"  name=\"documentid\"     value=\"" + document.getDocumentId()
                + "\" />");
        out.println("<input type=\"hidden\"  name=\"revisionid\"     value=\""
                + documentRevision.getRevisionId() + "\" />");
        out.println("<input type=\"submit\"  name=\"btnSubmit\"     value=\"" + "Save"
                + "\"    class=\"btn btn-sm btn-default\"/>");
        out.println("</form>");
        out.println("</div>");//panel-body
        out.println("</div>");//panel

        if (view.trim().length() <= 0) {
            out.println("<div class=\"well well-sm\">");
            if (acl.canDownload()) {
                out.println("<a href=\"/console/downloaddocument?documentid=" + document.getDocumentId()
                        + "&revisionid=" + documentRevision.getRevisionId()
                        + "\" class=\"btn btn-default btn-block \" title=\"Download Document\" ><i class=\"fa fa-download\"></i> Download Document</a>");
            }
            if (documentClass.isRevisionControlEnabled()) {
                if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE) && isHeadRevision) {
                    if (acl.canCheckout()) {
                        out.println("<a href=\"/console/checkoutdocument?documentid=" + document.getDocumentId()
                                + "\" class=\"btn btn-default btn-block \" title=\"Check Out Document\" ><i class=\"fa fa-lock\"></i> Check Out Document</a>");
                    }
                }
                if (document.getStatus().equalsIgnoreCase(Hit.STATUS_LOCKED)) {
                    out.println("<a href=\"/console/cancelcheckout?documentid=" + document.getDocumentId()
                            + "\" class=\"btn  btn-default btn-block confirm\" title=\"Are you sure, you want to cancel checkout of this document?\" ><i class=\"fa fa-unlock-alt\"></i> Cancel Checkout</a>");
                    if (acl.canCheckin()) {
                        out.println("<a href=\"/console/checkindocument?documentid=" + document.getDocumentId()
                                + "\" class=\"btn  btn-default btn-block \" title=\"Check In\" ><i class=\"fa fa-arrow-right\"></i> Check In</a>");
                    }
                }
                out.println("<a href=\"/console/revisionhistory?documentid=" + document.getDocumentId()
                        + "\" data-toggle=\"modal\" data-target=\"#revisionHistoryModal\" class=\"btn  btn-default btn-block \" title=\"Revision History\"><i class=\"fa fa-clock-o\"></i> Revision History</a>");
            }
            if (acl.canDelete() && document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)
                    && isHeadRevision) {
                out.println("<a href=\"/console/deletedocument?documentid=" + document.getDocumentId()
                        + "\" class=\"btn btn-danger btn-block confirm\" title=\"Are you sure, you want to mark this document as deleted?\" ><i class=\"fa fa-trash-o\"></i> Delete Document</a>");
            }
            out.println("</div>");//well well-sm
        }
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//tab-pane active #document

        out.println("<div class=\"tab-pane fade\" id=\"attachment\">");
        out.println(
                "<iframe frameborder=\"0\" border=\"0\" width=\"0\" height=\"0\" name=\"attachmentFrame\" id=\"attachmentFrame\" src=\"\" style=\"border:0px;\"></iframe>");

        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultAttachments\"></div>");
        out.println("</div>");//col-sm-9

        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println("<div class=\"panel-heading\"><i class=\"fa fa-paperclip\"></i> Add Attachment</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/attachments\" method=\"post\" id=\"frmAttachments\" name=\"frmAttachments\" enctype=\"multipart/form-data\" target=\"attachmentFrame\" accept-charset=\"utf-8\" class=\"internal\">");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"fileDocument\">Select Document <span style='color:red'>*</span></label>");
        out.println(
                "<input type=\"file\" name=\"fileDocument\" class=\"required\" title=\"Please select document\">");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"TITLE\">Attachment Title <span class=\"text-success\">*</span></label>");
        out.println(
                "<input type=\"text\" name=\"TITLE\" id=\"TITLE\" class=\"form-control required\" title=\"Please enter attachment title\" placeholder=\"Attachment Title\"/>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"KEYWORDS\">Attachment Keywords </label>");
        out.println(
                "<textarea name=\"KEYWORDS\" id=\"KEYWORDS\" rows=\"5\" class=\"form-control\" placeholder=\"Attachment Keywords\"></textarea>");
        out.println("</div>");

        out.println("<div class=\"form-group\" id=\"pbContainer\" style=\"display:none;\">");
        out.println("<div class=\"progress progress-striped active\" id=\"progressbarMain\">");
        out.println(
                "<div class=\"progress-bar progress-bar-success\" id=\"progressbar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 0%\">");
        out.println("<span class=\"sr-only\">0% Complete</span>");
        out.println("</div>");
        out.println("</div>");
        out.println(
                "<div id=\"progressMessage\" class=\"alert alert-success alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button></div>");
        out.println("</div>");

        out.println("<input type=\"hidden\" name=\"DOCID\" value=\"" + document.getDocumentId() + "\">");
        out.println("<input type=\"hidden\" name=\"REVISIONID\" value=\"" + documentRevision.getRevisionId()
                + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");
        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//panel-body
        out.println("</div>");//panel
        out.println("</div>");//tab-pane active #attachment

        out.println("<div class=\"tab-pane fade\" id=\"documentNotes\"><br/>");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultNotes\"></div>");//notes will be loaded here
        out.println("</div>");//col-sm-9
        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println(
                "<div class=\"panel-heading\"><i class=\"fa fa-comment-o fa-lg\"></i> Add Note / Comments</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/documentnotes\" id=\"frmNotes\" method=\"post\"  form-type=\"ajax\" datatarget=\"#resultNotes\">");
        out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"txtNote\">Note / Comments <span class=\"text-success\">*</span></label>");
        out.println(
                "<textarea name=\"txtNote\" id=\"txtNote\" rows=\"5\" class=\"form-control required alphaNumericSpace\" title=\"Please enter note\" placeholder=\"Note / Comments\"></textarea>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<div class=\"btn-group\" data-toggle=\"buttons\">");
        out.println("<label class=\"btn btn-sm btn-default active\">");
        out.println(
                "<input type=\"radio\" id=\"radNoteType1\" name=\"radNoteType\" value=\"P\" checked>Public");
        out.println("</label>");
        out.println("<label class=\"btn btn-sm btn-default\">");
        out.println("<input type=\"radio\" id=\"radNoteType2\" name=\"radNoteType\"  value=\"U\">Private");
        out.println("</label>");
        out.println("</div>");
        out.println("</div>");

        out.println("<hr/>");
        out.println("<input type=\"hidden\" name=\"documentid\" value=\"" + document.getDocumentId() + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Submit\" class=\"btn btn-sm btn-default\">");

        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row

        out.println("</div>");//panel-body
        out.println("</div>");//panel
        out.println("</div>");//tab-pane active #notes

        out.println("<div class=\"tab-pane fade\" id=\"accessHistory\"><br/>");
        out.println("<div class=\"row\">");
        out.println("<div class=\"col-sm-9\">");
        out.println("<div id=\"resultAccessHistory\"></div>");//access history will be loaded here
        out.println("</div>");//col-sm-9
        out.println("<div class=\"col-sm-3\">");
        out.println("<div class=\"panel panel-default\">");
        out.println(
                "<div class=\"panel-heading\"><i class=\"fa fa-filter fa-lg\"></i> Filter Access History</div>");
        out.println("<div class=\"panel-body\">");
        out.println(
                "<form action=\"/console/accesshistory\" id=\"frmAccessHistory\" method=\"post\" form-type=\"ajax\" datatarget=\"#resultAccessHistory\">");
        out.println("<div class=\"form-group\">");
        out.println("<label for=\"fromDate\">From</label>");
        out.println("<div class=\"input-group\">");
        out.println(
                "<input type=\"text\"  id=\"fromDate\" name=\"fromDate\" class=\"form-control shortdate isDate\">");
        out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
        out.println("</div>");
        out.println("</div>");

        out.println("<div class=\"form-group\">");
        out.println("<label for=\"toDate\">To</label>");
        out.println("<div class=\"input-group\">");
        out.println(
                "<input type=\"text\"  id=\"toDate\" name=\"toDate\" class=\" form-control shortdate isDate\">");
        out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
        out.println("</div>");
        out.println("</div>");

        out.println("<input type=\"hidden\" name=\"documentid\" value=\"" + document.getDocumentId() + "\">");
        out.println(
                "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Show Access History\" class=\"btn btn-sm btn-default btn-block\">");

        out.println("</form>");
        out.println("</div>");//col-sm-3
        out.println("</div>");//row
        out.println("</div>");//panel-body
        out.println("</div>");//panel

        out.println("</div>");//tab-pane active #accessHistory

        printModal("revisionHistoryModal");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    out.println("</div>");//tab-content
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

public void addPartition(String dbName, String tblName, AddPartitionDesc addPartitionDesc)
        throws InvalidObjectException, MetaException {
    boolean success = false;

    Connection con = null;/* w  w  w.  ja  v  a  2  s  .c  o  m*/
    PreparedStatement ps = null;
    Statement stmt = null;
    dbName = dbName.toLowerCase();
    tblName = tblName.toLowerCase();

    boolean isPathMaked = false;
    ArrayList<Path> pathToMake = new ArrayList<Path>();
    Warehouse wh = new Warehouse(hiveConf);

    long tblID = 0;

    try {
        con = getSegmentConnection(dbName);
    } catch (MetaStoreConnectException e1) {
        LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                + addPartitionDesc.getLevel() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                + addPartitionDesc.getLevel() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        stmt = con.createStatement();

        String tblType = null;
        boolean hasPriPart = false;
        boolean hasSubPart = false;
        String priPartKey = null;
        String subPartKey = null;
        String priPartType = null;
        String subPartType = null;

        String priKeyType = null;
        String subKeyType = null;
        ResultSet tblSet = null;
        boolean isTblFind = false;
        boolean isColFind = false;

        String tblFormat = null;
        String tblLocation = null;

        PrimitiveTypeInfo pti = null;
        ObjectInspector StringIO = null;
        ObjectInspector ValueIO = null;
        ObjectInspectorConverters.Converter converter1 = null;
        ObjectInspectorConverters.Converter converter2 = null;

        ArrayList<String> partToAdd = new ArrayList<String>();
        String sql = null;

        HiveConf hconf = (HiveConf) hiveConf;
        boolean externalPartition = hconf.getBoolVar(HiveConf.ConfVars.HIVESUPPORTEXTERNALPARTITION);

        if (addPartitionDesc.getLevel() == 0) {
            sql = "SELECT tbl_id, tbl_type, pri_part_type, pri_part_key, tbl_format, tbl_location"
                    + " from TBLS where db_name='" + dbName + "' and tbl_name='" + tblName + "'";

            tblSet = stmt.executeQuery(sql);
            isTblFind = false;

            while (tblSet.next()) {
                isTblFind = true;
                tblID = tblSet.getLong(1);
                tblType = tblSet.getString(2);
                priPartKey = tblSet.getString(4);
                priPartType = tblSet.getString(3);
                tblFormat = tblSet.getString(5);
                tblLocation = tblSet.getString(6);

                if (priPartType != null && !priPartType.isEmpty()) {
                    hasPriPart = true;
                }
                break;
            }
            tblSet.close();

            if (!isTblFind) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "can not find table " + dbName + ":"
                        + tblName);

                throw new MetaException("can not find table " + dbName + ":" + tblName);
            }

            if (!tblType.equalsIgnoreCase("MANAGED_TABLE")) {
                if (tblType.equalsIgnoreCase("EXTERNAL_TABLE") && tblFormat != null
                        && tblFormat.equalsIgnoreCase("pgdata")) {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + tblType + ":" + tblFormat
                            + " can not support alter partition");
                    throw new MetaException(tblType + ":" + tblFormat + " can not support alter partition");
                }

                if (externalPartition && tblType.equalsIgnoreCase("EXTERNAL_TABLE")
                        && (tblFormat == null || !tblFormat.equalsIgnoreCase("pgdata"))) {
                } else {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + tblType
                            + " can not support alter partition");

                    throw new MetaException(tblType + " can not support alter partition");
                }
            }

            if (!hasPriPart) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "table " + dbName + ":" + tblName
                        + " is not pri-partitioned");

                throw new MetaException("table " + dbName + ":" + tblName + " is not pri-partitioned");
            }

            sql = "SELECT type_name from COLUMNS where tbl_id=" + tblID + " and column_name='"
                    + priPartKey.toLowerCase() + "'";
            isColFind = false;
            ResultSet colSet = stmt.executeQuery(sql);
            while (colSet.next()) {
                isColFind = true;
                priKeyType = colSet.getString(1);
                break;
            }
            colSet.close();

            if (!isColFind) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "table "
                        + "can not find partition key information " + priPartKey);

                throw new MetaException("can not find partition key information " + priPartKey);
            }

            pti = new PrimitiveTypeInfo();
            pti.setTypeName(priKeyType);
            StringIO = PrimitiveObjectInspectorFactory
                    .getPrimitiveJavaObjectInspector(PrimitiveCategory.STRING);
            ValueIO = PrimitiveObjectInspectorFactory
                    .getPrimitiveWritableObjectInspector(pti.getPrimitiveCategory());
            converter1 = ObjectInspectorConverters.getConverter(StringIO, ValueIO);
            converter2 = ObjectInspectorConverters.getConverter(StringIO, ValueIO);

            if ((addPartitionDesc.getPartType().equalsIgnoreCase("RANGE_PARTITION")
                    && !priPartType.equalsIgnoreCase("range"))
                    || (addPartitionDesc.getPartType().equalsIgnoreCase("LIST_PARTITION")
                            && !priPartType.equalsIgnoreCase("list"))) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "can not add  a "
                        + addPartitionDesc.getPartType() + " partition, but the pri-partition type is "
                        + priPartType);

                throw new MetaException("can not add  a " + addPartitionDesc.getPartType()
                        + " partition, but the pri-partition type is " + priPartType);
            }

            LinkedHashMap<String, List<String>> partSpaces = new LinkedHashMap<String, List<String>>();
            Set<String> subPartNameSet = new TreeSet<String>();

            sql = "SELECT level, part_name, part_values from PARTITIONS where" + " tbl_id=" + tblID;// + " order by level asc";

            ResultSet partSet = stmt.executeQuery(sql);
            int partLevel = 0;

            while (partSet.next()) {
                partLevel = partSet.getInt(1);

                if (partLevel == 0) {
                    String partName = partSet.getString(2);
                    List<String> valueList = new ArrayList<String>();
                    Array spaceArray = partSet.getArray(3);

                    ResultSet priValueSet = spaceArray.getResultSet();

                    while (priValueSet.next()) {
                        valueList.add(priValueSet.getString(2));
                    }

                    partSpaces.put(partName, valueList);
                } else if (partLevel == 1) {
                    String partName = partSet.getString(2);
                    subPartNameSet.add(partName);
                }
            }
            partSet.close();

            partToAdd = new ArrayList<String>();

            LinkedHashMap<String, List<String>> addPartSpaces = (LinkedHashMap<String, List<String>>) addPartitionDesc
                    .getParSpaces();

            Iterator<String> itr = addPartSpaces.keySet().iterator();

            while (itr.hasNext()) {
                String key = itr.next().toLowerCase();
                if (partSpaces.containsKey(key)) {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + "table : " + tblName
                            + " have already contain a pri parititon named: " + key);

                    throw new MetaException(
                            "table : " + tblName + " have already contain a pri parititon named: " + key);
                }
                partToAdd.add(key);
            }

            Iterator<List<String>> listItr = addPartSpaces.values().iterator();

            while (listItr.hasNext()) {
                Iterator<String> valueItr = listItr.next().iterator();
                if (valueItr.hasNext()) {
                    String value = valueItr.next();

                    if (converter1.convert(value) == null) {
                        LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                                + addPartitionDesc.getLevel() + ", msg=" + "value : " + value
                                + " should be type of " + priKeyType);

                        throw new MetaException("value : " + value + " should be type of " + priKeyType);
                    }

                    Iterator<List<String>> PartValuesItr = partSpaces.values().iterator();
                    while (PartValuesItr.hasNext()) {
                        if (PartValuesItr.next().contains(value)) {
                            LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                                    + addPartitionDesc.getLevel() + ", msg=" + "table : " + tblName
                                    + " have already contain a pri partition contain value: " + value);

                            throw new MetaException("table : " + tblName
                                    + " have already contain a pri partition contain value: " + value);
                        }
                    }
                }
            }

            ps = con.prepareStatement(
                    "INSERT INTO partitions(level, tbl_id, " + " part_name, part_values) values(?,?,?,?)");

            for (Map.Entry<String, List<String>> entry : addPartSpaces.entrySet()) {
                ps.setInt(1, 0);
                ps.setLong(2, tblID);

                Array spaceArray = con.createArrayOf("varchar", entry.getValue().toArray());
                ps.setArray(4, spaceArray);
                ps.setString(3, entry.getKey());

                ps.addBatch();
            }
            ps.executeBatch();

            if (!tblType.equalsIgnoreCase("EXTERNAL_TABLE")) {
                for (String partName : partToAdd) {
                    if (tblLocation == null || tblLocation.trim().isEmpty()) {
                        pathToMake.addAll(wh.getPriPartitionPaths(dbName, tblName, partName, subPartNameSet));
                    } else {
                        pathToMake.addAll(Warehouse.getPriPartitionPaths(new Path(tblLocation), partName,
                                subPartNameSet));
                    }
                }
            } else {
                for (String partName : partToAdd) {
                    pathToMake.addAll(
                            Warehouse.getPriPartitionPaths(new Path(tblLocation), partName, subPartNameSet));
                }
            }
        } else if (addPartitionDesc.getLevel() == 1) {
            sql = "SELECT tbl_id, tbl_type, sub_part_type, sub_part_key, tbl_format, tbl_location"
                    + " from TBLS where db_name='" + dbName.toLowerCase() + "' and tbl_name='"
                    + tblName.toLowerCase() + "'";

            tblSet = stmt.executeQuery(sql);
            isTblFind = false;

            while (tblSet.next()) {
                isTblFind = true;
                tblID = tblSet.getLong(1);
                tblType = tblSet.getString(2);
                subPartKey = tblSet.getString(4);
                subPartType = tblSet.getString(3);
                tblFormat = tblSet.getString(5);
                tblLocation = tblSet.getString(6);

                if (subPartType != null && !subPartType.isEmpty()) {
                    hasSubPart = true;
                }

                break;
            }

            tblSet.close();
            if (!isTblFind) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "can not find table " + dbName + ":"
                        + tblName);

                throw new MetaException("can not find table " + dbName + ":" + tblName);
            }

            if (!tblType.equalsIgnoreCase("MANAGED_TABLE")) {
                if (tblType.equalsIgnoreCase("EXTERNAL_TABLE") && tblFormat != null
                        && tblFormat.equalsIgnoreCase("pgdata")) {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + tblType + ":" + tblFormat
                            + " can not support alter partition");
                    throw new MetaException(tblType + ":" + tblFormat + " can not support alter partition");
                }

                if (externalPartition && tblType.equalsIgnoreCase("EXTERNAL_TABLE")
                        && (tblFormat == null || !tblFormat.equalsIgnoreCase("pgdata"))) {
                } else {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + tblType
                            + " can not support alter partition");

                    throw new MetaException(tblType + " can not support alter partition");
                }
            }

            if (!hasSubPart) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "table " + dbName + ":" + tblName
                        + " is not sun-partitioned");

                throw new MetaException("table " + dbName + ":" + tblName + " is not sun-partitioned");
            }

            sql = "SELECT type_name from COLUMNS where tbl_id=" + tblID + " and column_name='"
                    + subPartKey.toLowerCase() + "'";

            isColFind = false;
            ResultSet colSet = stmt.executeQuery(sql);
            while (colSet.next()) {
                isColFind = true;
                subKeyType = colSet.getString(1);
                break;
            }

            colSet.close();

            if (!isColFind) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "can not find partition key information "
                        + priPartKey);

                throw new MetaException("can not find partition key information " + priPartKey);
            }

            pti = new PrimitiveTypeInfo();
            pti.setTypeName(subKeyType);
            StringIO = PrimitiveObjectInspectorFactory
                    .getPrimitiveJavaObjectInspector(PrimitiveCategory.STRING);
            ValueIO = PrimitiveObjectInspectorFactory
                    .getPrimitiveWritableObjectInspector(pti.getPrimitiveCategory());
            converter1 = ObjectInspectorConverters.getConverter(StringIO, ValueIO);
            converter2 = ObjectInspectorConverters.getConverter(StringIO, ValueIO);

            if ((addPartitionDesc.getPartType().equalsIgnoreCase("RANGE_PARTITION")
                    && !subPartType.equalsIgnoreCase("range"))
                    || (addPartitionDesc.getPartType().equalsIgnoreCase("LIST_PARTITION")
                            && !subPartType.equalsIgnoreCase("list"))) {
                LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                        + addPartitionDesc.getLevel() + ", msg=" + "you can not add  a "
                        + addPartitionDesc.getPartType() + " partition, but the sub-partition type is "
                        + subPartType);

                throw new MetaException("you can not add  a " + addPartitionDesc.getPartType()
                        + " partition, but the sub-partition type is " + subPartType);
            }

            LinkedHashMap<String, List<String>> partSpaces = new LinkedHashMap<String, List<String>>();
            Set<String> partNameSet = new TreeSet<String>();

            sql = "SELECT level,  part_name, part_values from PARTITIONS where" + " tbl_id=" + tblID;// + " order by level asc";

            ResultSet partSet = stmt.executeQuery(sql);
            int partLevel = 0;

            while (partSet.next()) {
                partLevel = partSet.getInt(1);

                if (partLevel == 1) {
                    String partName = partSet.getString(2);
                    List<String> valueList = new ArrayList<String>();
                    Array spaceArray = partSet.getArray(3);

                    ResultSet priValueSet = spaceArray.getResultSet();

                    while (priValueSet.next()) {
                        valueList.add(priValueSet.getString(2));
                    }
                    partSpaces.put(partName, valueList);
                } else if (partLevel == 0) {
                    String partName = partSet.getString(2);
                    partNameSet.add(partName);
                }
            }

            partToAdd = new ArrayList<String>();

            LinkedHashMap<String, List<String>> addPartSpaces = (LinkedHashMap<String, List<String>>) addPartitionDesc
                    .getParSpaces();

            Iterator<String> itr = addPartSpaces.keySet().iterator();

            while (itr.hasNext()) {
                String key = itr.next().toLowerCase();
                if (partSpaces.containsKey(key)) {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg=" + "table : " + tblName
                            + " have already contain a sub parititon named: " + key);

                    throw new MetaException(
                            "table : " + tblName + " have already contain a sub parititon named: " + key);
                }

                if (key.equalsIgnoreCase("default")) {
                    LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                            + addPartitionDesc.getLevel() + ", msg="
                            + "use : 'alter table tblname add default subpartition' to add default subpartition!");

                    throw new MetaException(
                            "use : 'alter table tblname add default subpartition' to add default subpartition!");
                }
                partToAdd.add(key);
            }

            Iterator<List<String>> listItr = addPartSpaces.values().iterator();

            while (listItr.hasNext()) {
                Iterator<String> valueItr = listItr.next().iterator();
                if (valueItr.hasNext()) {
                    String value = valueItr.next();

                    if (converter1.convert(value) == null) {
                        LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                                + addPartitionDesc.getLevel() + ", msg=" + "value : " + value
                                + " should be type of " + priKeyType);

                        throw new MetaException("value : " + value + " should be type of " + priKeyType);
                    }

                    Iterator<List<String>> PartValuesItr = partSpaces.values().iterator();
                    while (PartValuesItr.hasNext()) {
                        if (PartValuesItr.next().contains(value)) {
                            LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                                    + addPartitionDesc.getLevel() + ", msg=" + "table : " + tblName
                                    + " have already contain a sub partition contain value: " + value);

                            throw new MetaException("table : " + tblName
                                    + " have already contain a sub partition contain value: " + value);
                        }
                    }
                }
            }

            ps = con.prepareStatement(
                    "INSERT INTO partitions(level, tbl_id, " + " part_name, part_values) values(?,?,?,?)");

            for (Map.Entry<String, List<String>> entry : addPartSpaces.entrySet()) {
                ps.setInt(1, 1);
                ps.setLong(2, tblID);

                Array spaceArray = con.createArrayOf("varchar", entry.getValue().toArray());
                ps.setArray(4, spaceArray);
                ps.setString(3, entry.getKey());

                ps.addBatch();
            }
            ps.executeBatch();

            if (!tblType.equalsIgnoreCase("EXTERNAL_TABLE")) {
                for (String partName : partToAdd) {
                    if (tblLocation == null || tblLocation.trim().isEmpty()) {
                        pathToMake.addAll(wh.getSubPartitionPaths(dbName, tblName, partNameSet, partName));
                    } else {
                        pathToMake.addAll(
                                Warehouse.getSubPartitionPaths(new Path(tblLocation), partNameSet, partName));
                    }
                }
            } else {
                for (String partName : partToAdd) {
                    pathToMake.addAll(
                            Warehouse.getSubPartitionPaths(new Path(tblLocation), partNameSet, partName));
                }
            }
        }

        con.commit();
        success = true;
    } catch (SQLException ex) {
        ex.printStackTrace();
        LOG.error("add partition error, db=" + dbName + ", tbl=" + tblName + ", level="
                + addPartitionDesc.getLevel() + ", msg=" + ex.getMessage());

        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }

            if (isPathMaked) {
                for (Path path : pathToMake) {
                    wh.deleteDir(path, false);
                }
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    if (success) {
        boolean mkDirOK = false;
        List<Path> createdPath = new ArrayList<Path>();
        try {
            for (Path path : pathToMake) {
                mkDirOK = wh.mkdirs(path);
                if (!mkDirOK) {
                    break;
                }

                createdPath.add(path);
            }
        } catch (Exception x) {
            mkDirOK = false;
        }

        if (!mkDirOK) {
            dropPartitionMeta(dbName, tblID, addPartitionDesc);
            if (!createdPath.isEmpty()) {
                for (Path path : createdPath) {
                    wh.deleteDir(path, true);
                }
            }

            throw new MetaException("can not create hdfs path, add partition failed");
        }

    }
}