Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:org.apache.hadoop.mapred.lib.CombineFileInputFormat.java

/**
 * Return all the splits in the specified set of paths
 *//*from  ww w  .java2  s. c  o  m*/
private void getMoreSplits(JobConf job, Collection<LocatedFileStatus> stats, long maxSize, long minSizeNode,
        long minSizeRack, long maxNumBlocksPerSplit, List<CombineFileSplit> splits) throws IOException {

    // all blocks for all the files in input set
    OneFileInfo[] files;

    // mapping from a rack name to the list of blocks it has
    HashMap<String, List<OneBlockInfo>> rackToBlocks = new HashMap<String, List<OneBlockInfo>>();

    // mapping from a block to the nodes on which it has replicas
    HashMap<OneBlockInfo, String[]> blockToNodes = new HashMap<OneBlockInfo, String[]>();

    // mapping from a node to the list of blocks that it contains
    HashMap<String, List<OneBlockInfo>> nodeToBlocks = new HashMap<String, List<OneBlockInfo>>();

    if (stats.isEmpty()) {
        return;
    }
    files = new OneFileInfo[stats.size()];

    // populate all the blocks for all files
    long totLength = 0;
    int fileIndex = 0;
    for (LocatedFileStatus oneStatus : stats) {
        files[fileIndex] = new OneFileInfo(oneStatus, job,
                isSplitable(FileSystem.get(job), oneStatus.getPath()), rackToBlocks, blockToNodes, nodeToBlocks,
                rackToNodes, maxSize);
        totLength += files[fileIndex].getLength();
        fileIndex++;
    }

    // Sort the blocks on each node from biggest to smallest by size to
    // encourage more node-local single block splits
    sortBlocksBySize(nodeToBlocks);

    ArrayList<OneBlockInfo> validBlocks = new ArrayList<OneBlockInfo>();
    Set<String> nodes = new HashSet<String>();
    long curSplitSize = 0;

    // process all nodes and create splits that are local
    // to a node.
    for (Iterator<Map.Entry<String, List<OneBlockInfo>>> iter = nodeToBlocks.entrySet().iterator(); iter
            .hasNext();) {

        Map.Entry<String, List<OneBlockInfo>> one = iter.next();
        nodes.add(one.getKey());
        List<OneBlockInfo> blocksInNode = one.getValue();

        // for each block, copy it into validBlocks. Delete it from
        // blockToNodes so that the same block does not appear in
        // two different splits.
        for (OneBlockInfo oneblock : blocksInNode) {
            if (blockToNodes.containsKey(oneblock)) {
                validBlocks.add(oneblock);
                blockToNodes.remove(oneblock);
                curSplitSize += oneblock.length;

                // if the accumulated split size exceeds the maximum, then
                // create this split.
                if ((maxSize != 0 && curSplitSize >= maxSize)
                        || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
                    // create an input split and add it to the splits array
                    // if only one block, add all the node replicas
                    if (validBlocks.size() == 1) {
                        Set<String> blockLocalNodes = new HashSet<String>(
                                Arrays.asList(validBlocks.get(0).hosts));
                        addCreatedSplit(job, splits, blockLocalNodes, validBlocks);
                        addStatsForSplitType(SplitType.SINGLE_BLOCK_LOCAL, curSplitSize, blockLocalNodes.size(),
                                validBlocks.size());
                    } else {
                        addCreatedSplit(job, splits, nodes, validBlocks);
                        addStatsForSplitType(SplitType.NODE_LOCAL, curSplitSize, nodes.size(),
                                validBlocks.size());
                    }
                    curSplitSize = 0;
                    validBlocks.clear();
                }
            }
        }
        // if there were any blocks left over and their combined size is
        // larger than minSplitNode, then combine them into one split.
        // Otherwise add them back to the unprocessed pool. It is likely
        // that they will be combined with other blocks from the same rack later on.
        if (minSizeNode != 0 && curSplitSize >= minSizeNode) {
            // create an input split and add it to the splits array
            addCreatedSplit(job, splits, nodes, validBlocks);
            addStatsForSplitType(SplitType.NODE_LOCAL_LEFTOVER, curSplitSize, nodes.size(), validBlocks.size());
        } else {
            for (OneBlockInfo oneblock : validBlocks) {
                blockToNodes.put(oneblock, oneblock.hosts);
            }
        }
        validBlocks.clear();
        nodes.clear();
        curSplitSize = 0;
    }

    // if blocks in a rack are below the specified minimum size, then keep them
    // in 'overflow'. After the processing of all racks is complete, these overflow
    // blocks will be combined into splits.
    ArrayList<OneBlockInfo> overflowBlocks = new ArrayList<OneBlockInfo>();
    Set<String> racks = new HashSet<String>();

    // Process all racks over and over again until there is no more work to do.
    boolean noRacksMadeSplit = false;
    while (blockToNodes.size() > 0) {

        // Create one split for this rack before moving over to the next rack.
        // Come back to this rack after creating a single split for each of the
        // remaining racks.
        // Process one rack location at a time, Combine all possible blocks that
        // reside on this rack as one split. (constrained by minimum and maximum
        // split size).

        // Iterate over all racks.  Add to the overflow blocks only if at least
        // one pass over all the racks was completed without adding any splits
        long splitsAddedOnAllRacks = 0;
        for (Iterator<Map.Entry<String, List<OneBlockInfo>>> iter = rackToBlocks.entrySet().iterator(); iter
                .hasNext();) {

            Map.Entry<String, List<OneBlockInfo>> one = iter.next();
            racks.add(one.getKey());
            List<OneBlockInfo> blocks = one.getValue();

            // for each block, copy it into validBlocks. Delete it from
            // blockToNodes so that the same block does not appear in
            // two different splits.
            boolean createdSplit = false;
            for (OneBlockInfo oneblock : blocks) {
                if (blockToNodes.containsKey(oneblock)) {
                    validBlocks.add(oneblock);
                    blockToNodes.remove(oneblock);
                    curSplitSize += oneblock.length;

                    // if the accumulated split size exceeds the maximum, then
                    // create this split.
                    if ((maxSize != 0 && curSplitSize >= maxSize)
                            || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
                        // create an input split and add it to the splits array
                        addCreatedSplit(job, splits, getHosts(racks), validBlocks);
                        addStatsForSplitType(SplitType.RACK_LOCAL, curSplitSize, getHosts(racks).size(),
                                validBlocks.size());
                        createdSplit = true;
                        ++splitsAddedOnAllRacks;
                        break;
                    }
                }
            }

            // if we created a split, then just go to the next rack
            if (createdSplit) {
                curSplitSize = 0;
                validBlocks.clear();
                racks.clear();
                continue;
            }

            if (!validBlocks.isEmpty()) {
                if (minSizeRack != 0 && curSplitSize >= minSizeRack) {
                    // if there is a mimimum size specified, then create a single split
                    // otherwise, store these blocks into overflow data structure
                    addCreatedSplit(job, splits, getHosts(racks), validBlocks);
                    addStatsForSplitType(SplitType.RACK_LOCAL_LEFTOVER, curSplitSize, getHosts(racks).size(),
                            validBlocks.size());
                    ++splitsAddedOnAllRacks;
                } else if (!noRacksMadeSplit) {
                    // Add the blocks back if a pass on all rack found at least one
                    // split or this is the first pass
                    for (OneBlockInfo oneblock : validBlocks) {
                        blockToNodes.put(oneblock, oneblock.hosts);
                    }
                } else {
                    // There were a few blocks in this rack that remained to be processed.
                    // Keep them in 'overflow' block list. These will be combined later.
                    overflowBlocks.addAll(validBlocks);
                }
            }
            curSplitSize = 0;
            validBlocks.clear();
            racks.clear();
        }

        if (splitsAddedOnAllRacks == 0) {
            noRacksMadeSplit = true;
        }
    }

    assert blockToNodes.isEmpty();
    assert curSplitSize == 0;
    assert validBlocks.isEmpty();
    assert racks.isEmpty();

    // Process all overflow blocks
    for (OneBlockInfo oneblock : overflowBlocks) {
        validBlocks.add(oneblock);
        curSplitSize += oneblock.length;

        // This might cause an exiting rack location to be re-added,
        // but it should be OK because racks is a Set.
        for (int i = 0; i < oneblock.racks.length; i++) {
            racks.add(oneblock.racks[i]);
        }

        // if the accumulated split size exceeds the maximum, then
        // create this split.
        if ((maxSize != 0 && curSplitSize >= maxSize)
                || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
            // create an input split and add it to the splits array
            addCreatedSplit(job, splits, getHosts(racks), validBlocks);
            addStatsForSplitType(SplitType.OVERFLOW, curSplitSize, getHosts(racks).size(), validBlocks.size());
            curSplitSize = 0;
            validBlocks.clear();
            racks.clear();
        }
    }

    // Process any remaining blocks, if any.
    if (!validBlocks.isEmpty()) {
        addCreatedSplit(job, splits, getHosts(racks), validBlocks);
        addStatsForSplitType(SplitType.OVERFLOW_LEFTOVER, curSplitSize, getHosts(racks).size(),
                validBlocks.size());
    }
}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

public static ArrayList<SyncTaskItem> createSyncTaskList(Context context, GlobalParameters gp,
        CommonUtilities util, boolean sdcard, String fp, ArrayList<PreferenceParmListIItem> ispl) {
    ArrayList<SyncTaskItem> sync = new ArrayList<SyncTaskItem>();
    if (ispl != null)
        ispl.clear();

    if (sdcard) {
        File sf = new File(fp);
        if (sf.exists()) {
            CipherParms cp = null;/*from  ww w.jav a 2s  .  c o  m*/
            boolean prof_encrypted = isSyncTaskListFileEncrypted(fp);
            if (prof_encrypted) {
                cp = EncryptUtil.initDecryptEnv(gp.profileKeyPrefix + gp.profilePassword);
            }
            try {
                BufferedReader br;
                br = new BufferedReader(new FileReader(fp), 8192);
                String pl;
                while ((pl = br.readLine()) != null) {
                    String prof_pre = "";
                    prof_pre = SMBSYNC_PROF_VER1;
                    if (!pl.startsWith(prof_pre + SMBSYNC_PROF_ENC)
                            && !pl.startsWith(prof_pre + SMBSYNC_PROF_DEC)) {
                        if (prof_encrypted) {
                            String enc_str = pl.replace(prof_pre, "");
                            byte[] enc_array = Base64Compat.decode(enc_str, Base64Compat.NO_WRAP);
                            String dec_str = EncryptUtil.decrypt(enc_array, cp);
                            addSyncTaskList(prof_pre + dec_str, sync, ispl);
                        } else {
                            addSyncTaskList(pl, sync, ispl);
                        }
                    }
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            util.addLogMsg("E", String.format(context.getString(R.string.msgs_create_profile_not_found), fp));
        }
    } else {
        BufferedReader br;
        String pf = SMBSYNC_PROFILE_FILE_NAME_V1;
        try {
            File lf = new File(gp.applicationRootDirectory + "/" + pf);

            if (lf.exists()) {
                br = new BufferedReader(new FileReader(gp.applicationRootDirectory + "/" + pf), 8192);
                String pl;
                while ((pl = br.readLine()) != null) {
                    //                  Log.v("","read pl="+pl);
                    addSyncTaskList(pl, sync, ispl);
                }
                br.close();
            } else {
                util.addDebugMsg(1, "W", "profile not found, empty profile list created. fn="
                        + gp.applicationRootDirectory + "/" + pf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (sync.size() == 0) {
            if (BUILD_FOR_AMAZON) {
                //?????
            } else {
                if (gp.sampleProfileCreateRequired) {
                    createSampleSyncTask(sync);
                    saveSyncTaskListToFile(gp, context, util, false, "", "", sync, false);
                    gp.sampleProfileCreateRequired = false;
                }
            }
        }

    }

    sortSyncTaskList(sync);

    return sync;
}

From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java

/**
 * //w ww  .  j  a v a 2s .c om
 * @param params
 * @param thr
 * @return 
 */
public boolean compareProbParams(ArrayList<String> params, double thr) {
    //query for all problem ATTRIBUTES of each problem in localstore.        
    System.out.println("***************************************");
    System.out.println(
            "At this point we are checking if a similar problem " + "structure is present in the Case Base.");
    System.out.println("***************************************\n\n");
    StoredPaths pan = new StoredPaths();
    boolean isworthchecking = false;
    double similarity;
    ArrayList<ArrayList<String>> contents = new ArrayList<>();
    ArrayList<String> tempparam = new ArrayList<>();
    ArrayList<String> namelist = new ArrayList<>();
    String tempname = "";
    for (int i = 0; i < params.size(); i++) {
        String tempName = params.get(i);
        if (tempName.equals("ttl")) {
            params.remove(i);
        }
    }
    //Begin the initialisation process.
    OntModelSpec s = new OntModelSpec(OntModelSpec.OWL_DL_MEM);
    OntDocumentManager dm = OntDocumentManager.getInstance();
    dm.setFileManager(FileManager.get());
    s.setDocumentManager(dm);
    OntModel m = ModelFactory.createOntologyModel(s, null);
    InputStream in = FileManager.get().open(StoredPaths.casebasepath);
    if (in == null) {
        throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found");
    }
    // read the file
    m.read(in, null);
    //begin building query string.
    String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath;
    queryString += "\nSELECT distinct ?prob ?param WHERE { ?prob ?param ?value . ?prob base:hasCaseType \"problem\"^^xsd:string . filter isLiteral(?value) . ?param a owl:DatatypeProperty . filter not exists{  { filter regex(str(?value), \"problem\" )} union {?prob ?param true} union {?prob ?param false} } }";
    System.out.println("***************************************");
    System.out.println("Query String used: ");
    System.out.println(queryString);
    System.out.println("***************************************\n\n");
    try {
        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, m);
        ResultSet results = qe.execSelect();
        int i = 0;
        for (; results.hasNext();) {
            QuerySolution soln = results.nextSolution();
            // Access variables: soln.get("x");
            Resource res;
            Resource res2;
            res = soln.getResource("prob");// Get a result variable by name.
            if (!res.getURI().equalsIgnoreCase(tempname)) {
                tempname = res.getURI();
                namelist.add(res.getURI());
                i++;
                if (!tempparam.isEmpty())
                    contents.add(new ArrayList<>(tempparam));
                tempparam.clear();
            }
            res2 = soln.getResource("param");
            tempparam.add(res2.getURI().substring(res2.getURI().indexOf('#') + 1));
        }
        qe.close();
        contents.add(new ArrayList<>(tempparam));
    } catch (NumberFormatException e) {
        System.out.println("Query not valid.");
    }
    m.close();
    ArrayList<String> union = new ArrayList<>();
    ArrayList<String> intersection = new ArrayList<>();
    int i = 0;
    for (ArrayList<String> content : contents) {
        intersection.addAll(params);
        intersection.retainAll(content);
        union.addAll(content);
        similarity = intersection.size() / union.size();
        if (similarity >= thr) {
            isworthchecking = true;
            System.out.println("The Case is worth checking because of this " + similarity + " metric "
                    + "in problem identified as " + namelist.get(i) + ".");
        }
        i++;
        intersection.clear();
        union.clear();
    }
    return isworthchecking;
}

From source file:com.concursive.connect.web.portal.PortletManager.java

/**
 * @param context  The portal application's ActionContext
 * @param db       The database connection the page can use
 * @param thisPage The dashboard page to be rendered
 * @return if processing results in the portlet manager taking control of the dispatching for this request
 * @throws Exception any error/*from   w  ww.ja va 2s  . c  o  m*/
 */
public static boolean processPage(ActionContext context, Connection db, DashboardPage thisPage)
        throws Exception {

    LOG.debug("processPage");

    ApplicationPrefs applicationPrefs = (ApplicationPrefs) context.getServletContext()
            .getAttribute("applicationPrefs");
    User user = (User) context.getSession().getAttribute(Constants.SESSION_USER);

    // The portal is using parameters in the URL, instead of directories, so enable them
    ArrayList<String> moduleParamNames = new ArrayList<String>();
    if (!thisPage.getObjectType().equals(DashboardTemplateList.TYPE_NAVIGATION)) {
        moduleParamNames.add("command");
        moduleParamNames.add("section");
        moduleParamNames.add("pid");
        moduleParamNames.add("dash");
        moduleParamNames.add("name");
        moduleParamNames.add("popup");
    }
    context.getRequest().setAttribute(PortalURLParserImpl.ALLOWED_PORTAL_PARAMETERS, moduleParamNames);

    // Populate the principal user that is required by the ProxyPortlet to establish sessions
    Map userInfo = new HashMap();
    userInfo.put("map", "init");
    userInfo.put("user.sessionId", String.valueOf(context.getSession().getId()));
    if (user != null) {
        userInfo.put("user.key", String.valueOf(user.getId()));
        userInfo.put("user.name.given", user.getFirstName());
        userInfo.put("user.name.family", user.getLastName());
    } else {
        userInfo.put("user.key", "-2");
        userInfo.put("user.name.given", "Guest");
    }
    context.getRequest().setAttribute("proxyportlet.user.info", userInfo);

    // Override Pluto's default mechanism for PortalURL
    PortalURLParser parser = null;
    if (thisPage.getObjectType().equals(DashboardTemplateList.TYPE_NAVIGATION)) {
        parser = ProjectPortalURLParserImpl.getParser();
    } else {
        parser = PortalURLParserImpl.getParser();
    }
    context.getRequest().setAttribute("ConcursivePortalURLParser", parser);

    // Get the portlet container
    PortletContainer container = (PortletContainer) context.getServletContext()
            .getAttribute("PortletContainer");

    // Initialize the portlet mappings
    String applicationId = checkRegistryService(context.getServletContext(),
            context.getServlet().getServletConfig(), context.getRequest());

    // Register ConcourseConnect consumer with the remote wsrp producer
    boolean isConsumerRegistered = checkServicesRegistry(context.getServletContext(), applicationPrefs);

    // Maintain the context for portlet communication this request
    PortalRequestContext portalRequestContext = new PortalRequestContext(context.getServletContext(),
            context.getRequest(), context.getResponse());
    PortalURL portalURL = portalRequestContext.getRequestedPortalURL();

    HashMap<String, Object> eventData = new HashMap<String, Object>();

    // NOTE: WSRP requires a context path to use the resource proxy, however, this prevents WSRP
    // from using the actual web-apps contextPath so URLs cannot be based on that
    String ctx = context.getRequest().getContextPath();
    if (!StringUtils.hasText(ctx)) {
        ctx = "/PlutoInvoker";
    }
    // Override WSRP's context path locator because it can't find a root context
    context.getServletContext().setAttribute(ConsumerConstants.WSRP_PORTLET_CONTEXT_PATH, ctx);

    // Build a list of portlets to process for this request
    ArrayList<PortletTask> portlets = new ArrayList<PortletTask>();

    // Priority 1: Process the lone action if there is one
    // Priority 2: Check the portlet windowState and portletMode so that only
    // the portlet being edited or the portlet that is maximized is rendered
    // Priority 3: Render portlets that generate events
    // Priority 4: Render all the other portlets
    // NOTE: Some portals like to show the minimized portlets in some way,
    // especially when editing content

    // Iterate the specific portlets on this page and add them for processing later
    int maximizedModeId = -1;
    int editModeId = -1;
    String actionWindowId = portalURL.getActionWindow();
    for (DashboardPortlet thisPortlet : thisPage.getPortletList()) {
        // Handle ProxyPortlet instances
        if ("ProxyPortlet".equals(thisPortlet.getName())) {
            if (!isConsumerRegistered) {
                continue;
            }
            // Set the default portlet settings
            DashboardPortletPrefs portletHandle = thisPortlet.getDefaultPreferences()
                    .get(ConsumerConstants.WSRP_PORTLET_HANDLE);
            DashboardPortletPrefs producerId = new DashboardPortletPrefs(ConsumerConstants.WSRP_PRODUCER_ID,
                    PortletManager.CONCURSIVE_WSRP_PRODUCER_ID);
            DashboardPortletPrefs parentHandle = new DashboardPortletPrefs(ConsumerConstants.WSRP_PARENT_HANDLE,
                    portletHandle.getValues());
            // Inject proxy portlet preferences
            thisPortlet.getDefaultPreferences().put(ConsumerConstants.WSRP_PRODUCER_ID, producerId);
            thisPortlet.getDefaultPreferences().put(ConsumerConstants.WSRP_PARENT_HANDLE, parentHandle);
            // @todo if the portlet handle changed for this user, then do something...
            LOG.debug("portletHandle: " + portletHandle.getValue());
            LOG.debug("producerId: " + producerId.getValue());
            LOG.debug("parentHandle: " + parentHandle.getValue());
        }

        // Each portlet needs its own PortletWindow
        String windowConfigId;
        if (thisPortlet.getLoaded()) {
            windowConfigId = applicationId + "." + thisPortlet.getName() + "!" + thisPortlet.getId();
        } else {
            windowConfigId = applicationId + "." + thisPortlet.getName() + "!T" + thisPortlet.getId();
        }
        PortletWindowConfig windowConfig = PortletWindowConfig.fromId(windowConfigId);
        //windowConfig.setContextPath(context.getRequest().getContextPath());
        PortletWindowImpl portletWindow = new PortletWindowImpl(windowConfig, portalURL);
        // NOTE: potential concern when using different parsers
        thisPortlet.setWindowConfigId(PortalURLParserImpl.encodeCharacters(windowConfigId));
        thisPortlet.setPageName(thisPage.getName());

        // A single action
        if (actionWindowId != null) {
            if (actionWindowId.equals(portletWindow.getId().getStringId())) {
                portlets.add(new PortletTask(thisPortlet, portletWindow));
                break;
            }
            continue;
        }

        // A single edited portlet
        if (portletWindow.getPortletMode().equals(PortletMode.EDIT)) {
            portlets.clear();
            portlets.add(new PortletTask(thisPortlet, portletWindow));
            editModeId = thisPortlet.getId();
            break;
        }

        // A single maximized portlet
        if (portletWindow.getWindowState().equals(WindowState.MAXIMIZED)) {
            portlets.clear();
            portlets.add(new PortletTask(thisPortlet, portletWindow));
            maximizedModeId = thisPortlet.getId();
            break;
        }

        // Add generator portlets at the beginning
        if (!thisPortlet.getGenerateDataEvents().isEmpty()) {
            portlets.add(0, new PortletTask(thisPortlet, portletWindow));
        } else {
            portlets.add(new PortletTask(thisPortlet, portletWindow));
        }
    }
    context.getRequest().setAttribute("editModeId", editModeId);
    context.getRequest().setAttribute("maximizedModeId", maximizedModeId);

    // If ACTION then only the portlet the action for is executed
    if (actionWindowId != null) {
        PortletTask thisTask = portlets.get(0);
        DashboardPortlet thisPortlet = thisTask.getPortlet();
        PortletWindowImpl portletWindow = thisTask.getWindow();

        // Pass the request to the specified doAction
        // Since this is an embedded container, portlets can access the data store directly
        portalRequestContext.getRequest().setAttribute("connection", db);
        portalRequestContext.getRequest().setAttribute("dashboardPage", thisPage);
        portalRequestContext.getRequest().setAttribute("applicationPrefs", applicationPrefs);
        portalRequestContext.getRequest().setAttribute("user", user);
        portalRequestContext.getRequest().setAttribute("dashboardPortlet", thisPortlet);
        portalRequestContext.getRequest().setAttribute("objectHookManager",
                context.getServletContext().getAttribute("ObjectHookManager"));
        portalRequestContext.getRequest().setAttribute("scheduler",
                context.getServletContext().getAttribute("Scheduler"));
        portalRequestContext.getRequest().setAttribute("freemarkerConfiguration",
                context.getServletContext().getAttribute("FreemarkerConfiguration"));
        portalRequestContext.getRequest().setAttribute("TEAM.KEY",
                context.getServletContext().getAttribute("TEAM.KEY"));
        //portalRequestContext.getRequest().setAttribute("proxyportlet.user.info", context.getRequest().getAttribute("proxyportlet.user.info"));
        // If this portlet is requesting session data, provide it to the portlet
        if (!thisPortlet.getConsumeSessionData().isEmpty()) {
            for (String data : thisPortlet.getConsumeSessionData()) {
                String contextName = context.getRequest().getContextPath();
                if (contextName.startsWith("/")) {
                    contextName = contextName.substring(1);
                }
                // javax.portlet.p./.RegisterPortlet!T1?TEST=VALUE
                // javax.portlet.p./contextname.RegisterPortlet!T1?TEST=VALUE
                String sessionName = "javax.portlet.p./" + contextName + "." + thisPortlet.getName() + "!T"
                        + thisPortlet.getId() + "?" + data;
                context.getSession().setAttribute(sessionName, context.getSession().getAttribute(data));
            }
        }
        // provide the application's url
        portalRequestContext.getRequest().setAttribute("url",
                "http://" + RequestUtils.getServerUrl(context.getRequest()));
        // provide the secure url if enabled
        boolean sslEnabled = "true".equals(applicationPrefs.get("SSL"));
        String url = ("http" + (sslEnabled ? "s" : "") + "://"
                + RequestUtils.getServerUrl(context.getRequest()));
        portalRequestContext.getRequest().setAttribute("secureUrl", url);
        try {
            container.doAction(portletWindow, portalRequestContext.getRequest(), context.getResponse());
            // @todo I think, if the WSRP portlet handle changed for this user, then record it here so that it can be used on the next request...
        } catch (PortletContainerException ex) {
            throw new ServletException(ex);
        } catch (PortletException ex) {
            throw new ServletException(ex);
        }
        LOG.debug("Action request processed.");
        // no more processing is needed, a portlet action was found
        return true;
    }

    // Render the portlets
    for (PortletTask task : portlets) {
        try {
            DashboardPortlet thisPortlet = task.getPortlet();

            // Bypass ProxyPortlet instances if consumer is not yet registered
            if ("ProxyPortlet".equals(thisPortlet.getName()) && !isConsumerRegistered) {
                continue;
            }

            PortletWindowImpl portletWindow = task.getWindow();
            // Each uses a request/response
            PortalServletRequest portalRequest = new PortalServletRequest(context.getRequest(), portletWindow);
            PortalServletResponse portalResponse = new PortalServletResponse(context.getResponse());
            // The context path to be used for parsing pluto portlet references
            String contextName = context.getRequest().getContextPath();
            if (contextName != null && contextName.startsWith("/")) {
                contextName = contextName.substring(1);
            }

            // Provide objects to the embedded portlets
            portalRequest.setAttribute("connection", db);
            portalRequest.setAttribute("dashboardPage", thisPage);
            portalRequest.setAttribute("applicationPrefs", applicationPrefs);
            portalRequest.setAttribute("user", context.getSession().getAttribute(Constants.SESSION_USER));
            portalRequest.setAttribute("dashboardPortlet", thisPortlet);
            portalRequest.setAttribute("objectHookManager",
                    context.getServletContext().getAttribute("ObjectHookManager"));
            portalRequest.setAttribute("scheduler", context.getServletContext().getAttribute("Scheduler"));
            portalRequest.setAttribute("freemarkerConfiguration",
                    context.getServletContext().getAttribute("FreemarkerConfiguration"));
            portalRequest.setAttribute("projectSearcher", context.getRequest().getAttribute("projectSearcher"));
            portalRequest.setAttribute("baseQueryString", context.getRequest().getAttribute("baseQueryString"));
            portalRequest.setAttribute("TEAM.KEY", context.getServletContext().getAttribute("TEAM.KEY"));
            portalRequest.setAttribute(AbstractPortletModule.COMMAND, thisPortlet.getViewer());
            //portalRequest.setAttribute("proxyportlet.user.info", context.getRequest().getAttribute("proxyportlet.user.info"));
            // Framework display parameters
            portalRequest.setAttribute("popup", context.getRequest().getParameter("popup"));
            // Script Node and XHR DataSources
            portalRequest.setAttribute("query", context.getRequest().getParameter("query"));
            // provide the application's url
            portalRequest.setAttribute("url", "http://" + RequestUtils.getServerUrl(context.getRequest()));
            // provide the secure url if enabled
            boolean sslEnabled = "true".equals(applicationPrefs.get("SSL"));
            String url = ("http" + (sslEnabled ? "s" : "") + "://"
                    + RequestUtils.getServerUrl(context.getRequest()));
            portalRequest.setAttribute("secureUrl", url);

            // If this portlet is requesting data, provide it to the portlet
            if (!thisPortlet.getConsumeDataEvents().isEmpty()) {
                for (String event : thisPortlet.getConsumeDataEvents()) {
                    portalRequest.setAttribute("event" + event, eventData.get(event));
                }
            }

            // Render the portlet, and have the PortalURL know which portlet is being rendered
            LOG.debug("Render windowId: " + portletWindow.getId().getStringId());
            portalURL.setRenderPath(portletWindow.getId().getStringId());

            // Add the base params to this portlet
            if (parser instanceof ProjectPortalURLParserImpl) {
                LOG.debug("Adding all non-portlet specific parameters to portlet scope");
                ProjectPortalURLParserImpl.addAllParameters(context.getRequest(), portalURL);
            }

            boolean renderedNewPortlet = renderPortlet(context, container, thisPage, thisPortlet, portletWindow,
                    portalRequest, portalResponse, isConsumerRegistered);
            if (!renderedNewPortlet) {
                continue;
            }

            // If this portlet is sharing data, and the portlet was just rendered, then get it from the portlet and request
            if (!thisPortlet.getGenerateDataEvents().isEmpty()) {
                if (LOG.isInfoEnabled()) {
                    Enumeration test = portalRequest.getAttributeNames();
                    while (test.hasMoreElements()) {
                        String thisName = (String) test.nextElement();
                        LOG.debug("Request attribute: " + thisName);
                    }
                }
                for (String event : thisPortlet.getGenerateDataEvents()) {
                    // Pluto_/.SearchResultsByProjectPortlet!T3_hits
                    // Pluto_/team/.SearchResultsByProjectPortlet!T3_hits
                    String thisPortletEvent = "Pluto_/" + contextName + "." + thisPortlet.getName() + "!T"
                            + thisPortlet.getId() + "_event" + event;
                    Object thisEvent = portalRequest.getAttribute(thisPortletEvent);
                    if (thisEvent == null) {
                        LOG.error("Shared event not found in context (" + contextName + ") : " + event);
                    }
                    eventData.put(event, portalRequest.getAttribute(thisPortletEvent));
                }
            }
            // If this portlet is sharing request data, then get it from the portlet
            if (!thisPortlet.getGenerateRequestData().isEmpty()) {
                for (String attribute : thisPortlet.getGenerateRequestData()) {
                    String thisPortletAttributeName = "Pluto_/" + contextName + "." + thisPortlet.getName()
                            + "!T" + thisPortlet.getId() + "_" + attribute;
                    Object thisAttribute = portalRequest.getAttribute(thisPortletAttributeName);
                    if (thisAttribute == null) {
                        LOG.error("Shared request object not found in context (" + contextName + ") : "
                                + attribute);
                    }
                    portalRequest.setAttribute(attribute, thisAttribute);
                }
            }
        } catch (Exception e) {
            LOG.error("Error loading portlet: " + e.getMessage());
            e.printStackTrace(System.out);
        }
    }
    return false;
}

From source file:com.clustercontrol.jobmanagement.factory.JobSessionJobImpl.java

/**
 * ????/*w ww . j ava 2 s .  c  o m*/
 *
 * @param sessionId ID
 * @param jobId ID
 * @return 
 * @throws JobInfoNotFound
 */
protected Integer checkEndStatus(String sessionId, String jobunitId, String jobId)
        throws JobInfoNotFound, InvalidRole {

    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();

    m_log.debug("checkEndStatus() : sessionId=" + sessionId + ", jobId=" + jobId);

    //ID?ID???
    JobSessionJobEntity sessionJob = QueryUtil.getJobSessionJobPK(sessionId, jobunitId, jobId);
    // ?
    JobInfoEntity job = sessionJob.getJobInfoEntity();

    ArrayList<Integer> statusList = new ArrayList<Integer>();

    if (sessionJob.getJobInfoEntity().getJobType() == JobConstant.TYPE_JOB
            || sessionJob.getJobInfoEntity().getJobType() == JobConstant.TYPE_APPROVALJOB
            || sessionJob.getJobInfoEntity().getJobType() == JobConstant.TYPE_MONITORJOB) {
        //??

        //??
        Collection<JobSessionNodeEntity> collection = sessionJob.getJobSessionNodeEntities();
        for (JobSessionNodeEntity sessionNode : sessionJob.getJobSessionNodeEntities()) {

            Integer endValue = sessionNode.getEndValue();
            if (endValue == null) {
                continue;
            }
            Integer status = null;
            if (endValue >= job.getNormalEndValueFrom() && endValue <= job.getNormalEndValueTo()) {
                //??????
                status = EndStatusConstant.TYPE_NORMAL;
                statusList.add(status);
            } else if (endValue >= job.getWarnEndValueFrom() && endValue <= job.getWarnEndValueTo()) {
                //??????
                status = EndStatusConstant.TYPE_WARNING;
                statusList.add(status);
            } else {
                //??????
                status = EndStatusConstant.TYPE_ABNORMAL;
                statusList.add(status);
            }

            //???????
            if (job.getProcessMode() == ProcessingMethodConstant.TYPE_RETRY
                    && status == EndStatusConstant.TYPE_NORMAL) {
                statusList.clear();
                statusList.add(EndStatusConstant.TYPE_NORMAL);
                break;
            }
        }
        //???????
        if (collection.size() == 0) {
            statusList.clear();
            statusList.add(EndStatusConstant.TYPE_ABNORMAL);
        }
    } else {
        //??

        Integer endStatusCheck = sessionJob.getEndStausCheckFlg();
        if (endStatusCheck == null || endStatusCheck == EndStatusCheckConstant.NO_WAIT_JOB) {
            //???????????

            //ID?ID???
            Collection<JobSessionJobEntity> collection = QueryUtil.getChildJobSessionJob(sessionId, jobunitId,
                    jobId);

            for (JobSessionJobEntity childSessionJob : collection) {

                //????????
                Collection<JobStartJobInfoEntity> targetJobList = null;
                targetJobList = em
                        .createNamedQuery("JobStartJobInfoEntity.findByTargetJobId",
                                JobStartJobInfoEntity.class)
                        .setParameter("sessionId", sessionId)
                        .setParameter("targetJobId", childSessionJob.getId().getJobId()).getResultList();

                if (targetJobList.size() > 0) {
                    continue;
                }

                //?????????????
                Integer endValue = childSessionJob.getEndValue();
                if (endValue >= job.getNormalEndValueFrom() && endValue <= job.getNormalEndValueTo()) {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_NORMAL);
                } else if (endValue >= job.getWarnEndValueFrom() && endValue <= job.getWarnEndValueTo()) {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_WARNING);
                } else {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_ABNORMAL);
                }
            }
            //???????
            if (collection.size() == 0) {
                statusList.clear();
                statusList.add(EndStatusConstant.TYPE_ABNORMAL);
            }
        } else {
            //?

            //ID?ID???
            Collection<JobSessionJobEntity> collection = QueryUtil.getChildJobSessionJob(sessionId, jobunitId,
                    jobId);

            for (JobSessionJobEntity childSessionJob : collection) {

                Integer endValue = childSessionJob.getEndValue();
                if (endValue >= job.getNormalEndValueFrom() && endValue <= job.getNormalEndValueTo()) {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_NORMAL);
                } else if (endValue >= job.getWarnEndValueFrom() && endValue <= job.getWarnEndValueTo()) {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_WARNING);
                } else {
                    //??????
                    statusList.add(EndStatusConstant.TYPE_ABNORMAL);
                }
            }
            //???????
            if (collection.size() == 0) {
                statusList.clear();
                statusList.add(EndStatusConstant.TYPE_ABNORMAL);
            }
        }
    }

    //?
    Integer endStatus = EndJudgment.judgment(statusList);

    return endStatus;
}

From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java

public ArrayList<ArrayList<String>> searchIotService(String domain) {
    ArrayList<ArrayList<String>> solution = new ArrayList<>();
    int i = 0;// ww  w .  j  av a2  s . c  o  m
    String servicename;
    String prevser = "";
    String prevURI = "";
    String URI;
    ArrayList<String> paramname = new ArrayList<>();
    ArrayList<String> respname = new ArrayList<>();
    StoredPaths pan = new StoredPaths();
    OntModel m = createModel(StoredPaths.servicepath);
    //begin building query string.
    String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixServicePath;
    queryString += "\nselect distinct ?service ?URI ?namep ?namer " + "where{?service base:isServiceOf base:"
            + domain + " . " + "?service base:usesComponent ?comp . ?comp base:hasRESTParameter ?param . "
            + "?comp base:hasRESTResponce ?resp . ?comp base:accessURI ?URI . "
            + "?param base:hasName ?namep . ?resp base:hasName ?namer} order by ?service ?namer";
    System.out.println(queryString);
    try {
        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, m);
        ResultSet results = qe.execSelect();
        for (; results.hasNext();) {
            QuerySolution soln = results.nextSolution();
            // Access variables: soln.get("x");
            Resource res = soln.getResource("service");
            Literal lit = soln.getLiteral("URI");
            Literal lit2 = soln.getLiteral("namep");
            Literal lit3 = soln.getLiteral("namer");
            servicename = res.getURI().substring(res.getURI().indexOf('#') + 1);
            URI = lit.getString();

            if (prevser.equalsIgnoreCase("") && prevURI.equalsIgnoreCase("")) {
                prevser = servicename;
                prevURI = URI;
                respname.add(lit3.getString());
                respname.add("^");
                paramname.add(lit2.getString());
                paramname.add("^");
            }
            if (!servicename.equalsIgnoreCase(prevser)) {
                solution.add(new ArrayList<>(Arrays.asList(prevser, "^", prevURI)));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                paramname.remove(paramname.size() - 1);
                solution.add(new ArrayList<>(paramname));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                respname.remove(respname.size() - 1);
                solution.add(new ArrayList<>(respname));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                prevser = servicename;
                prevURI = URI;
                paramname.clear();
                respname.clear();
            }
            if (!paramname.contains(lit2.getString())) {
                paramname.add(lit2.getString());
                paramname.add("^");
            }
            if (!lit3.getString().equalsIgnoreCase(respname.get(i))) {
                respname.add(lit3.getString());
                respname.add("^");
                //paramname.clear();
                i++;
                i++;
            }
        }
        solution.add(new ArrayList<>(Arrays.asList(prevser, "^", prevURI)));
        solution.add(new ArrayList<>(Arrays.asList("&")));
        paramname.remove(paramname.size() - 1);
        solution.add(new ArrayList<>(paramname));
        solution.add(new ArrayList<>(Arrays.asList("&")));
        respname.remove(respname.size() - 1);
        solution.add(new ArrayList<>(respname));
        //solution.add(new ArrayList<>(Arrays.asList("&")));
        qe.close();
    } catch (NumberFormatException e) {
        System.out.println("Query not valid.");
    }
    m.close();
    return solution;
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of sites given a parent site
* @param parentSite the site to search for subsites, empty string for root
* @return lists of sites as an arraylist of NameValue objects
*///from   www  . j ava 2  s  .  c  o  m
public List<NameValue> getSites(String parentSite) throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        // Call the webs service
        if (parentSite.equals("/"))
            parentSite = "";
        WebsWS webService = new WebsWS(baseUrl + parentSite, userName, password, configuration, httpClient);
        WebsSoap webCall = webService.getWebsSoapHandler();

        GetWebCollectionResponseGetWebCollectionResult webResp = webCall.getWebCollection();
        org.apache.axis.message.MessageElement[] webList = webResp.get_any();

        XMLDoc doc = new XMLDoc(webList[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'ns1:Webs' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }
        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:Webs"))
            throw new ManifoldCFException("Bad xml - outer node is not 'ns1:Webs'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Webs>

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);
            //Logging.connectors.debug( i + ": " + o );
            //System.out.println( i + ": " + o );
            String url = doc.getValue(o, "Url");
            String title = doc.getValue(o, "Title");

            // Leave here for now
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("SharePoint: Subsite list: '" + url + "', '" + title + "'");

            // A full path to the site is tacked on the front of each one of these.  However, due to nslookup differences, we cannot guarantee that
            // the server name part of the path will actually match what got passed in.  Therefore, we want to look only at the last path segment, whatever that is.
            if (url != null && url.length() > 0) {
                int lastSlash = url.lastIndexOf("/");
                if (lastSlash != -1) {
                    String pathValue = url.substring(lastSlash + 1);
                    if (pathValue.length() > 0) {
                        if (title == null || title.length() == 0)
                            title = pathValue;
                        result.add(new NameValue(pathValue, title));
                    }
                }
            }
        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting subsites for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to get subsites of site "
                                        + parentSite + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + parentSite + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception getting subsites for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }

}

From source file:com.google.blockly.model.BlockFactory.java

/**
 * Generate a {@link Block} from JSON, including all inputs and fields within the block.
 *
 * @param type The type id of the block.
 * @param json The JSON to generate the block from.
 *
 * @return The generated Block.//  w  w  w  .ja v a  2s  .c o m
 * @throws BlockLoadingException if the json is malformed.
 */
public Block fromJson(String type, JSONObject json) throws BlockLoadingException {
    if (TextUtils.isEmpty(type)) {
        throw new IllegalArgumentException("Block type may not be null or empty.");
    }
    if (json == null) {
        throw new IllegalArgumentException("Json may not be null.");
    }
    Block.Builder builder = new Block.Builder(type);

    if (json.has("output") && json.has("previousStatement")) {
        throw new BlockLoadingException("Block cannot have both an output and a previous statement.");
    }

    // Parse any connections that are present.
    if (json.has("output")) {
        String[] checks = Input.getChecksFromJson(json, "output");
        Connection output = new Connection(Connection.CONNECTION_TYPE_OUTPUT, checks);
        builder.setOutput(output);
    } else if (json.has("previousStatement")) {
        String[] checks = Input.getChecksFromJson(json, "previousStatement");
        Connection previous = new Connection(Connection.CONNECTION_TYPE_PREVIOUS, checks);
        builder.setPrevious(previous);
    }
    // A block can have either an output connection or previous connection, but it can always
    // have a next connection.
    if (json.has("nextStatement")) {
        String[] checks = Input.getChecksFromJson(json, "nextStatement");
        Connection next = new Connection(Connection.CONNECTION_TYPE_NEXT, checks);
        builder.setNext(next);
    }
    if (json.has("inputsInline")) {
        try {
            builder.setInputsInline(json.getBoolean("inputsInline"));
        } catch (JSONException e) {
            // Do nothing and it will remain false.
        }
    }

    int blockColor = ColorUtils.DEFAULT_BLOCK_COLOR;
    if (json.has("colour")) {
        try {
            String colourString = json.getString("colour");
            blockColor = ColorUtils.parseColor(colourString, TEMP_IO_THREAD_FLOAT_ARRAY,
                    ColorUtils.DEFAULT_BLOCK_COLOR);
        } catch (JSONException e) {
            // Won't get here. Checked above.
        }
    }
    builder.setColor(blockColor);

    ArrayList<Input> inputs = new ArrayList<>();
    ArrayList<Field> fields = new ArrayList<>();
    for (int i = 0;; i++) {
        String messageKey = "message" + i;
        String argsKey = "args" + i;
        String lastDummyAlignKey = "lastDummyAlign" + i;
        if (!json.has(messageKey)) {
            break;
        }
        String message = json.optString(messageKey);
        JSONArray args = json.optJSONArray(argsKey);
        if (args == null) {
            // If there's no args for this message use an empty array.
            args = new JSONArray();
        }

        if (message.matches("^%[a-zA-Z][a-zA-Z_0-9]*$")) {
            // TODO(#83): load the message from resources.
        }
        // Split on all argument indices of the form "%N" where N is a number from 1 to
        // the number of args without removing them.
        List<String> tokens = Block.tokenizeMessage(message);
        int indexCount = 0;
        // Indices start at 1, make the array 1 bigger so we don't have to offset things
        boolean[] seenIndices = new boolean[args.length() + 1];

        for (String token : tokens) {
            // Check if this token is an argument index of the form "%N"
            if (token.matches("^%\\d+$")) {
                int index = Integer.parseInt(token.substring(1));
                if (index < 1 || index > args.length()) {
                    throw new BlockLoadingException("Message index " + index + " is out of range.");
                }
                if (seenIndices[index]) {
                    throw new BlockLoadingException(("Message index " + index + " is duplicated"));
                }
                seenIndices[index] = true;

                JSONObject element;
                try {
                    element = args.getJSONObject(index - 1);
                } catch (JSONException e) {
                    throw new BlockLoadingException("Error reading arg %" + index, e);
                }
                while (element != null) {
                    String elementType = element.optString("type");
                    if (TextUtils.isEmpty(elementType)) {
                        throw new BlockLoadingException("No type for arg %" + index);
                    }

                    if (Field.isFieldType(elementType)) {
                        fields.add(loadFieldFromJson(type, element));
                        break;
                    } else if (Input.isInputType(elementType)) {
                        Input input = Input.fromJson(element);
                        input.addAll(fields);
                        fields.clear();
                        inputs.add(input);
                        break;
                    } else {
                        // Try getting the fallback block if it exists
                        Log.w(TAG, "Unknown element type: " + elementType);
                        element = element.optJSONObject("alt");
                    }
                }
            } else {
                token = token.replace("%%", "%").trim();
                if (!TextUtils.isEmpty(token)) {
                    fields.add(new FieldLabel(null, token));
                }
            }
        }

        // Verify every argument was used
        for (int j = 1; j < seenIndices.length; j++) {
            if (!seenIndices[j]) {
                throw new BlockLoadingException("Argument " + j + " was never used.");
            }
        }
        // If there were leftover fields we need to add a dummy input to hold them.
        if (fields.size() != 0) {
            String align = json.optString(lastDummyAlignKey, Input.ALIGN_LEFT_STRING);
            Input input = new Input.InputDummy(null, align);
            input.addAll(fields);
            inputs.add(input);
            fields.clear();
        }
    }

    builder.setInputs(inputs);
    return builder.build();
}

From source file:op.care.nursingprocess.PnlNursingProcess.java

private JPanel getMenu(final NursingProcess np) {

    final JPanel pnlMenu = new JPanel(new VerticalLayout());
    long numDFNs = DFNTools.getNumDFNs(np);

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***// w  w w  .ja v a 2  s  . c  o  m
         *       ____ _
         *      / ___| |__   __ _ _ __   __ _  ___
         *     | |   | '_ \ / _` | '_ \ / _` |/ _ \
         *     | |___| | | | (_| | | | | (_| |  __/
         *      \____|_| |_|\__,_|_| |_|\__, |\___|
         *                              |___/
         */
        JButton btnChange = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnchange.tooltip",
                SYSConst.icon22playerPlay, null);
        btnChange.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                NursingProcess template = np.clone();
                template.setTo(SYSConst.DATE_UNTIL_FURTHER_NOTICE);
                template.setUserOFF(null);
                template.setUserON(OPDE.getLogin().getUser());
                template.setNextEval(new DateTime().plusWeeks(4).toDate());
                new DlgNursingProcess(template, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                // Fetch the new Plan from the PAIR
                                NursingProcess myNewNP = em.merge(
                                        ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o).getFirst());
                                NursingProcess myOldNP = em.merge(np);
                                em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                // Close old NP
                                myOldNP.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                myOldNP.setTo(new DateTime().minusSeconds(1).toDate());
                                NPControl lastValidation = em
                                        .merge(new NPControl(myNewNP.getSituation(), myOldNP));
                                lastValidation.setLastValidation(true);
                                myOldNP.getEvaluations().add(lastValidation);

                                // Starts 1 second after the old one stopped
                                myNewNP.setFrom(new DateTime(myOldNP.getTo()).plusSeconds(1).toDate());

                                // Create new DFNs according to plan
                                DFNTools.generate(em, myNewNP.getInterventionSchedule(), new LocalDate(), true);
                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myOldNP.getCategory()).add(myOldNP);
                                valuecache.get(myNewNP.getCategory()).add(myNewNP);
                                Collections.sort(valuecache.get(myNewNP.getCategory()));
                                createCP4(myNewNP.getCategory());

                                boolean reloadSearch = false;
                                for (Commontags ctag : myNewNP.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }

                                buildPanel();
                                GUITools.flashBackground(contenPanelMap.get(myNewNP), Color.YELLOW, 2);
                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                            //                                reloadTable();
                        }
                    }
                });

            }
        });
        btnChange.setEnabled(!np.isClosed() && numDFNs != 0);
        pnlMenu.add(btnChange);

        /***
         *      ____        _   _                ____  _
         *     | __ ) _   _| |_| |_ ___  _ __   / ___|| |_ ___  _ __
         *     |  _ \| | | | __| __/ _ \| '_ \  \___ \| __/ _ \| '_ \
         *     | |_) | |_| | |_| || (_) | | | |  ___) | || (_) | |_) |
         *     |____/ \__,_|\__|\__\___/|_| |_| |____/ \__\___/| .__/
         *                                                     |_|
         */

        final JButton btnStop = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnstop.tooltip",
                SYSConst.icon22stop, null);
        btnStop.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnStop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                JPanel dlg = new PnlEval(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            popup.hidePopup();

                            Pair<NursingProcess, String> result = (Pair<NursingProcess, String>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                NursingProcess myOldNP = em.merge(np);
                                em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                myOldNP.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                myOldNP.setTo(new Date());
                                NPControl lastValidation = em.merge(new NPControl(result.getSecond(), myOldNP));
                                lastValidation.setLastValidation(true);
                                myOldNP.getEvaluations().add(lastValidation);

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myOldNP.getCategory()).add(myOldNP);
                                Collections.sort(valuecache.get(myOldNP.getCategory()));

                                createCP4(myOldNP.getCategory());
                                buildPanel();
                                //                                    GUITools.flashBackground(contenPanelMap.get(myOldNP), Color.YELLOW, 2);

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                            OPDE.getDisplayManager()
                                    .addSubMessage(DisplayManager.getSuccessMessage(np.getTopic(), "closed"));
                            reloadDisplay();
                        }
                    }
                }, true);

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(dlg);
                popup.setOwner(btnStop);
                popup.removeExcludedComponent(btnStop);
                popup.setDefaultFocusComponent(dlg);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnStop.setEnabled(!np.isClosed() && numDFNs != 0);
        pnlMenu.add(btnStop);

        /***
         *      ____        _   _                _____    _ _ _
         *     | __ ) _   _| |_| |_ ___  _ __   | ____|__| (_) |_
         *     |  _ \| | | | __| __/ _ \| '_ \  |  _| / _` | | __|
         *     | |_) | |_| | |_| || (_) | | | | | |__| (_| | | |_
         *     |____/ \__,_|\__|\__\___/|_| |_| |_____\__,_|_|\__|
         *
         */

        JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnedit.tooltip",
                SYSConst.icon22edit, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgNursingProcess(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                NursingProcess mynp = em.merge(
                                        ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o).getFirst());
                                em.lock(mynp, LockModeType.OPTIMISTIC);
                                // Schedules to delete
                                for (InterventionSchedule is : ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o)
                                        .getSecond()) {
                                    em.remove(em.merge(is));
                                }
                                // No unused DFNs to delete
                                Query delQuery = em.createQuery(
                                        "DELETE FROM DFN dfn WHERE dfn.nursingProcess = :nursingprocess ");
                                delQuery.setParameter("nursingprocess", mynp);
                                delQuery.executeUpdate();
                                // Create new DFNs according to plan
                                DFNTools.generate(em, mynp.getInterventionSchedule(), new LocalDate(), true);
                                em.getTransaction().commit();

                                boolean reloadSearch = false;
                                for (Commontags ctag : mynp.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(mynp.getCategory()).add(mynp);
                                Collections.sort(valuecache.get(mynp.getCategory()));

                                createCP4(mynp.getCategory());
                                buildPanel();
                                GUITools.flashBackground(contenPanelMap.get(mynp), Color.YELLOW, 2);

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                            //                                reloadTable();
                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(!np.isClosed() && numDFNs == 0);
        pnlMenu.add(btnEdit);
    }

    /***
     *      ____        _   _                ____       _      _
     *     | __ ) _   _| |_| |_ ___  _ __   |  _ \  ___| | ___| |_ ___
     *     |  _ \| | | | __| __/ _ \| '_ \  | | | |/ _ \ |/ _ \ __/ _ \
     *     | |_) | |_| | |_| || (_) | | | | | |_| |  __/ |  __/ ||  __/
     *     |____/ \__,_|\__|\__\___/|_| |_| |____/ \___|_|\___|\__\___|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) { // => ACL_MATRIX
        JButton btnDelete = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btndelete.tooltip",
                SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><b>" + np.getTopic() + "</b><br/>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o.equals(JOptionPane.YES_OPTION)) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        NursingProcess myOldNP = em.merge(np);
                                        em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                        // DFNs to delete
                                        Query delQuery = em.createQuery(
                                                "DELETE FROM DFN dfn WHERE dfn.nursingProcess = :nursingprocess ");
                                        delQuery.setParameter("nursingprocess", myOldNP);
                                        //                                    delQuery.setParameter("status", DFNTools.STATE_OPEN);
                                        delQuery.executeUpdate();

                                        em.remove(myOldNP);
                                        em.getTransaction().commit();

                                        // Refresh Display
                                        valuecache.get(np.getCategory()).remove(np);
                                        contenPanelMap.remove(np);

                                        createCP4(myOldNP.getCategory());
                                        buildPanel();

                                        OPDE.getDisplayManager().addSubMessage(
                                                DisplayManager.getSuccessMessage(np.getTopic(), "deleted"));

                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(!np.isClosed() && numDFNs == 0);
        pnlMenu.add(btnDelete);
    }

    /***
     *      ____  _         _____            _
     *     | __ )| |_ _ __ | ____|_   ____ _| |
     *     |  _ \| __| '_ \|  _| \ \ / / _` | |
     *     | |_) | |_| | | | |___ \ V / (_| | |
     *     |____/ \__|_| |_|_____| \_/ \__,_|_|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        final JButton btnEval = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btneval.tooltip",
                SYSConst.icon22redo, null);
        btnEval.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEval.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                JPanel dlg = new PnlEval(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            popup.hidePopup();

                            Pair<NursingProcess, String> result = (Pair<NursingProcess, String>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                NursingProcess evaluatedNP = em.merge(result.getFirst());
                                em.lock(evaluatedNP, LockModeType.OPTIMISTIC);

                                NPControl newEvaluation = em
                                        .merge(new NPControl(result.getSecond(), evaluatedNP));
                                evaluatedNP.getEvaluations().add(newEvaluation);

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(evaluatedNP.getCategory()).add(evaluatedNP);
                                Collections.sort(valuecache.get(evaluatedNP.getCategory()));

                                createCP4(evaluatedNP.getCategory());
                                buildPanel();
                                GUITools.flashBackground(contenPanelMap.get(evaluatedNP), Color.YELLOW, 2);

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                            OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                                    SYSTools.xx("nursingrecords.nursingprocess.success.neweval")));
                            reloadDisplay();
                        }
                    }
                }, false);

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(dlg);
                popup.setOwner(btnEval);
                popup.removeExcludedComponent(btnEval);
                popup.setDefaultFocusComponent(dlg);

                GUITools.showPopup(popup, SwingConstants.NORTH_WEST);
            }
        });

        btnEval.setEnabled(!np.isClosed());
        pnlMenu.add(btnEval);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(np.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {

                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            NursingProcess myNP = em.merge(np);
                            em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            myNP.getCommontags().clear();
                            for (Commontags commontag : pnlCommonTags.getListSelectedTags()) {
                                myNP.getCommontags().add(em.merge(commontag));
                            }

                            em.getTransaction().commit();

                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            boolean reloadSearch = false;
                            for (Commontags ctag : myNP.getCommontags()) {
                                if (!listUsedCommontags.contains(ctag)) {
                                    listUsedCommontags.add(ctag);
                                    reloadSearch = true;
                                }
                            }
                            if (reloadSearch) {
                                prepareSearchArea();
                            }

                            createCP4(myNP.getCategory());
                            buildPanel();
                            GUITools.flashBackground(contenPanelMap.get(myNP), Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            } else {
                                reloadDisplay();
                            }
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(!np.isClosed());
        pnlMenu.add(btnTAGs);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                        em.close();
                        // Refresh Display
                        valuecache.get(np.getCategory()).remove(np);
                        contenPanelMap.remove(np);
                        valuecache.get(myNP.getCategory()).add(myNP);
                        Collections.sort(valuecache.get(myNP.getCategory()));

                        createCP4(myNP.getCategory());
                        buildPanel();
                    }
                };
                new DlgFiles(np, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            final NursingProcess myNP = em.merge(np);
                            em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSNP2PROCESS> attached = new ArrayList<SYSNP2PROCESS>(
                                    myNP.getAttachedQProcessConnections());
                            for (SYSNP2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getNursingProcess().getAttachedQProcessConnections()
                                            .remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myNP.getTitle() + " ID: " + myNP.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                java.util.List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myNP)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSNP2PROCESS myLinkObject = em.merge(new SYSNP2PROCESS(myQProcess, myNP));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myNP.getTitle() + " ID: " + myNP.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedNursingProcessesConnections().add(myLinkObject);
                                    myNP.getAttachedQProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            createCP4(myNP.getCategory());
                            buildPanel();

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            } else {
                                reloadDisplay();
                            }
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }

                    }
                });
            }
        });
        btnProcess.setEnabled(!np.isClosed());
        pnlMenu.add(btnProcess);

    }
    return pnlMenu;
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of document libraries given a parent site
* @param parentSite the site to search for document libraries, empty string for root
* @return lists of NameValue objects, representing document libraries
*//* w  ww.j  av a  2s .  co  m*/
public List<NameValue> getDocumentLibraries(String parentSite, String parentSiteDecoded)
        throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        String parentSiteRequest = parentSite;

        if (parentSiteRequest.equals("/")) {
            parentSiteRequest = ""; // root case
            parentSiteDecoded = "";
        }

        ListsWS listsService = new ListsWS(baseUrl + parentSiteRequest, userName, password, configuration,
                httpClient);
        ListsSoap listsCall = listsService.getListsSoapHandler();

        GetListCollectionResponseGetListCollectionResult listResp = listsCall.getListCollection();
        org.apache.axis.message.MessageElement[] lists = listResp.get_any();

        //if ( parentSite.compareTo("/Sample2") == 0) System.out.println( lists[0].toString() );

        XMLDoc doc = new XMLDoc(lists[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'ns1:Lists' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }
        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:Lists"))
            throw new ManifoldCFException("Bad xml - outer node is not 'ns1:Lists'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Lists>

        String prefixPath = decodedServerLocation + parentSiteDecoded + "/";

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);

            String baseType = doc.getValue(o, "BaseType");
            if (baseType.equals("1")) {
                // We think it's a library

                // This is how we display it, so this has the right path extension
                String urlPath = doc.getValue(o, "DefaultViewUrl");
                // This is the pretty name
                String title = doc.getValue(o, "Title");

                // Leave this in for the moment
                if (Logging.connectors.isDebugEnabled())
                    Logging.connectors.debug("SharePoint: Library list: '" + urlPath + "', '" + title + "'");

                // It's a library.  If it has no view url, we don't have any idea what to do with it
                if (urlPath != null && urlPath.length() > 0) {
                    // Normalize conditionally
                    if (!urlPath.startsWith("/"))
                        urlPath = prefixPath + urlPath;
                    // Get rid of what we don't want, unconditionally
                    if (urlPath.startsWith(prefixPath)) {
                        urlPath = urlPath.substring(prefixPath.length());
                        // We're at the library name.  Figure out where the end of it is.
                        int index = urlPath.indexOf("/");
                        if (index == -1)
                            throw new ManifoldCFException(
                                    "Bad library view url without site: '" + urlPath + "'");
                        String pathpart = urlPath.substring(0, index);

                        if (pathpart.length() != 0 && !pathpart.equals("_catalogs")) {
                            if (title == null || title.length() == 0)
                                title = pathpart;
                            result.add(new NameValue(pathpart, title));
                        }
                    } else {
                        Logging.connectors.warn("SharePoint: Library view url is not in the expected form: '"
                                + urlPath + "'; expected something beginning with '" + prefixPath
                                + "'; skipping");
                    }
                }
            }
        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting document libraries for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to read document libraries for site "
                                        + parentSite + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + parentSite + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception reading document libraries for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }
}