Example usage for java.util.concurrent ConcurrentHashMap get

List of usage examples for java.util.concurrent ConcurrentHashMap get

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentHashMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:spade.utility.BitcoinTools.java

public void writeBlocksToCSV(int startIndex, int endIndex) {
    // Block block, int lastBlockId
    int lastBlockId = -1;
    final BitcoinTools bitcoinTools = new BitcoinTools();

    String pattern = "#.##";
    DecimalFormat decimalFormat = new DecimalFormat(pattern);

    final ConcurrentHashMap<Integer, Block> blockMap = new ConcurrentHashMap<Integer, Block>();
    final AtomicInteger currentBlock = new AtomicInteger(startIndex);
    final int stopIndex = endIndex;
    final int totalThreads = Runtime.getRuntime().availableProcessors();

    class BlockFetcher implements Runnable {

        public void run() {

            while (true) {
                if (blockMap.size() > totalThreads * 5) { // max objects to hold in memory max 1 MB * totalThreads * factor
                    try {
                        Thread.sleep(100);
                        continue;
                    } catch (Exception exception) {
                    }/* w ww.  j av a2  s.c o m*/
                }

                int blockToFetch = currentBlock.getAndIncrement();
                try {
                    blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                } catch (JSONException exception) {
                    Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " has invalid json. Redownloading.",
                            exception);
                    try {
                        blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                    } catch (JSONException ex) {
                        Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " couldn't be included in CSV.",
                                ex);
                    }
                }
                if (blockToFetch >= stopIndex) {
                    break;
                }
            }
        }
    }

    ArrayList<Thread> workers = new ArrayList<Thread>();
    for (int i = 0; i < totalThreads; i++) {
        Thread th = new Thread(new BlockFetcher());
        workers.add(th);
        th.start();
    }

    int percentageCompleted = 0;

    for (int i = startIndex; i < endIndex; i++) {

        try {

            Block block;
            while (!blockMap.containsKey(i)) {

            }
            block = blockMap.get(i);
            blockMap.remove(i);
            lastBlockId = writeBlockToCSV(block, lastBlockId);

            if ((((i - startIndex + 1) * 100) / (endIndex - startIndex)) > percentageCompleted) {
                Runtime rt = Runtime.getRuntime();
                long totalMemory = rt.totalMemory() / 1024 / 1024;
                long freeMemory = rt.freeMemory() / 1024 / 1024;
                long usedMemory = totalMemory - freeMemory;
                System.out.print("| Cores: " + rt.availableProcessors() + " | Threads: " + totalThreads
                        + " | Heap (MB) - total: " + totalMemory + ", %age free: "
                        + (freeMemory * 100) / totalMemory + " | At Block: " + (i - startIndex + 1) + " / "
                        + (endIndex - startIndex) + " | Percentage Completed: " + percentageCompleted
                        // + " |\r");
                        + " |\n");
            }

            percentageCompleted = ((i - startIndex + 1) * 100) / (endIndex - startIndex);

        } catch (IOException ex) {
            Bitcoin.log(Level.SEVERE, "Unexpected IOException. Stopping CSV creation.", ex);
            break;
        }
    }

    for (int i = 0; i < totalThreads; i++) {
        try {
            workers.get(i).interrupt();
            workers.get(i).join();
        } catch (InterruptedException exception) {
        }
    }

    System.out.println("\n\ndone with creating CSVes!");
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ObjectNode buildLinksNode(final ObjectMapper objectMapper, final Map<URI, ObjectNode> schemaNodes,
        final Map<URI, LinkRelation> linkRelationCache, final ApiNavigator apiNavigator,
        final Resource resource, final Prototype defaultPrototype) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null;

    final ObjectNode linksNode = objectMapper.createObjectNode();

    final Set<URI> responseSchemaUris = new HashSet<>();
    if (defaultSchemaUri != null) {
        responseSchemaUris.add(defaultSchemaUri);
    }//from ww w .  ja va  2 s  .c  o m

    for (final Method method : Method.values()) {
        final Set<URI> methodResponseSchemaUris = resource.getResponseSchemaUris(method);
        if (methodResponseSchemaUris != null && !methodResponseSchemaUris.isEmpty()) {
            responseSchemaUris.addAll(methodResponseSchemaUris);
        }
    }

    final ConcurrentHashMap<URI, LinkTemplate> linkTemplates = resource.getLinkTemplates();

    for (final URI schemaUri : responseSchemaUris) {
        final Prototype prototype = schemaLoader.getPrototype(schemaUri);
        final SortedMap<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots();
        if (linkProtoSlots == null || linkProtoSlots.isEmpty()) {
            continue;
        }

        final ObjectNode linkTemplatesNode = objectMapper.createObjectNode();

        final Set<URI> linkRelationUris = linkProtoSlots.keySet();
        for (final URI linkRelationUri : linkRelationUris) {
            final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(linkRelationUri);

            if (schemaLoader.getDocumentSchemaUri().equals(linkProtoSlot.getDeclaringSchemaUri())) {
                // Skip over the built-in system-level link relations (which are all self-referential).
                continue;
            }

            final ObjectNode linkTemplateNode = objectMapper.createObjectNode();
            final String linkSlotName = linkProtoSlot.getName();
            linkTemplatesNode.put(linkSlotName, linkTemplateNode);

            final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);
            final Method method = linkRelation.getMethod();

            linkTemplateNode.put(PropertyName.method.name(), method.getProtocolGivenName());
            linkTemplateNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));
            linkTemplateNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle());

            final URI responseSchemaUri;
            final URI requestSchemaUri;

            if (linkTemplates.containsKey(linkRelationUri)) {
                final LinkTemplate linkTemplate = linkTemplates.get(linkRelationUri);
                responseSchemaUri = linkTemplate.getResponseSchemaUri();
                requestSchemaUri = linkTemplate.getRequestSchemaUri();

                final UUID endPointId = linkTemplate.getEndPointId();
                if (endPointId != null) {
                    final Resource endPointResource = apiNavigator.getResource(endPointId);

                    final ObjectNode endPointNode = objectMapper.createObjectNode();

                    endPointNode.put(PropertyName.id.name(), syntaxLoader.formatSyntaxValue(endPointId));
                    endPointNode.put(PropertyName.pathSegment.name(), endPointResource.getPathSegment());
                    endPointNode.put(PropertyName.fullPath.name(), endPointResource.getPathText());
                    endPointNode.put(PropertyName.uriTemplate.name(),
                            endPointResource.getUriTemplate().getUriTemplateString());

                    linkTemplateNode.put(PropertyName.endpoint.name(), endPointNode);
                }

            } else {
                responseSchemaUri = linkProtoSlot.getResponseSchemaUri();
                requestSchemaUri = linkProtoSlot.getRequestSchemaUri();
            }

            if (responseSchemaUri != null) {
                final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                        responseSchemaUri, schemaLoader);
                linkTemplateNode.put(PropertyName.responseSchema.name(), responseSchemaNode);
            }

            if (requestSchemaUri != null) {
                final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes, requestSchemaUri,
                        schemaLoader);
                linkTemplateNode.put(PropertyName.requestSchema.name(), requestSchemaNode);
            }

            final String signature = buildLinkSignature(linkSlotName, responseSchemaUri, requestSchemaUri,
                    schemaUri);
            linkTemplateNode.put(PropertyName.signature.name(), signature);
        }

        if (linkTemplatesNode.size() > 0) {
            final ObjectNode schemaNode = objectMapper.createObjectNode();
            final ObjectNode schemaDetailsNode = getSchemaNode(objectMapper, schemaNodes, schemaUri,
                    schemaLoader);
            schemaNode.put(PropertyName.schema.name(), schemaDetailsNode);
            schemaNode.put(PropertyName.linkTemplates.name(), linkTemplatesNode);
            linksNode.put(prototype.getUniqueName().getLocalName(), schemaNode);
        }
    }

    return linksNode;
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.ComBat.java

private void runNonParametric(final DoubleMatrix2D sdata, DoubleMatrix2D gammastar, DoubleMatrix2D deltastar) {
    final ConcurrentHashMap<String, DoubleMatrix1D[]> results = new ConcurrentHashMap<>();
    int numThreads = Math.min(batches.size(), Runtime.getRuntime().availableProcessors());

    ComBat.log.info("Runing nonparametric estimation on " + numThreads + " threads");

    Future<?>[] futures = new Future[numThreads];
    ExecutorService service = Executors.newCachedThreadPool();

    /*/*from   w ww.j a v a  2  s.  c  o  m*/
     * Divvy up batches over threads.
     */

    int batchesPerThread = batches.size() / numThreads;

    final String[] batchIds = batches.keySet().toArray(new String[] {});

    for (int i = 0; i < numThreads; i++) {

        final int firstBatch = i * batchesPerThread;
        final int lastBatch = i == (numThreads - 1) ? batches.size() : firstBatch + batchesPerThread;

        futures[i] = service.submit(new Runnable() {
            @Override
            public void run() {
                for (int k = firstBatch; k < lastBatch; k++) {
                    String batchId = batchIds[k];
                    DoubleMatrix2D batchData = ComBat.this.getBatchData(sdata, batchId);
                    DoubleMatrix1D[] batchResults = ComBat.this.nonParametricFit(batchData, gammaHat.viewRow(k),
                            deltaHat.viewRow(k));
                    results.put(batchId, batchResults);
                }
            }
        });
    }

    service.shutdown();

    boolean allDone = false;
    do {
        for (Future<?> f : futures) {
            allDone = true;
            if (!f.isDone() && !f.isCancelled()) {
                allDone = false;
                break;
            }
        }
    } while (!allDone);

    for (int i = 0; i < batchIds.length; i++) {
        String batchId = batchIds[i];
        DoubleMatrix1D[] batchResults = results.get(batchId);
        for (int j = 0; j < batchResults[0].size(); j++) {
            gammastar.set(i, j, batchResults[0].get(j));
        }
        for (int j = 0; j < batchResults[1].size(); j++) {
            deltastar.set(i, j, batchResults[1].get(j));
        }
    }
}

From source file:eu.itesla_project.online.db.OnlineDbMVStore.java

private void serializeStoredWorkflowsStates() {
    LOGGER.info("Serializing stored workflows states");
    for (String workflowId : workflowsStates.keySet()) {
        if (workflowStatesFolderExists(workflowId)) {
            LOGGER.info("Serializing network data of workflow {}", workflowId);
            ConcurrentHashMap<Integer, Map<HistoDbAttributeId, Object>> workflowStates = workflowsStates
                    .get(workflowId);//from  w ww.j  a  v a  2s  .  c  om
            Path workflowStatesFolder = getWorkflowStatesFolder(workflowId);
            Path csvFile = Paths.get(workflowStatesFolder.toString(), SERIALIZED_STATES_FILENAME);
            try (FileWriter fileWriter = new FileWriter(csvFile.toFile());
                    CsvListWriter csvWriter = new CsvListWriter(fileWriter,
                            new CsvPreference.Builder('"', ';', "\r\n").build())) {
                boolean printHeaders = true;
                for (Integer stateId : workflowStates.keySet()) {
                    Map<HistoDbAttributeId, Object> networkValues = workflowStates.get(stateId);
                    if (printHeaders) {
                        List<String> headers = new ArrayList<>(networkValues.size());
                        for (HistoDbAttributeId attrId : networkValues.keySet()) {
                            headers.add(attrId.toString());
                        }
                        ArrayList<String> headersList = new ArrayList<>();
                        headersList.add("workflow");
                        headersList.add("state");
                        headersList.addAll(Arrays.asList(headers.toArray(new String[] {})));
                        csvWriter.writeHeader(headersList.toArray(new String[] {}));
                        printHeaders = false;
                    }
                    ArrayList<Object> valuesList = new ArrayList<>();
                    valuesList.add(workflowId);
                    valuesList.add(stateId);
                    valuesList.addAll(Arrays.asList(networkValues.values().toArray()));
                    csvWriter.write(valuesList.toArray());
                }
            } catch (IOException e) {
                LOGGER.error("Error serializing network data for workflow {}", workflowId);
            }
        }
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);//from   w w w  .jav  a 2  s .  c om
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

From source file:ubic.gemma.analysis.preprocess.batcheffects.ComBat.java

/**
 * Multithreaded//www.ja v  a2  s.c o m
 * 
 * @param sdata
 * @param gammastar
 * @param deltastar
 */
private void runNonParametric(final DoubleMatrix2D sdata, DoubleMatrix2D gammastar, DoubleMatrix2D deltastar) {
    final ConcurrentHashMap<String, DoubleMatrix1D[]> results = new ConcurrentHashMap<String, DoubleMatrix1D[]>();
    int numThreads = Math.min(batches.size(), Runtime.getRuntime().availableProcessors());

    log.info("Runing nonparametric estimation on " + numThreads + " threads");

    Future<?>[] futures = new Future[numThreads];
    ExecutorService service = Executors.newCachedThreadPool();

    /*
     * Divvy up batches over threads.
     */

    int batchesPerThread = batches.size() / numThreads;

    final String[] batchIds = batches.keySet().toArray(new String[] {});

    for (int i = 0; i < numThreads; i++) {

        final int firstBatch = i * batchesPerThread;
        final int lastBatch = i == (numThreads - 1) ? batches.size() : firstBatch + batchesPerThread;

        futures[i] = service.submit(new Runnable() {
            @Override
            public void run() {
                for (int k = firstBatch; k < lastBatch; k++) {
                    String batchId = batchIds[k];
                    DoubleMatrix2D batchData = getBatchData(sdata, batchId);
                    DoubleMatrix1D[] batchResults = nonParametricFit(batchData, gammaHat.viewRow(k),
                            deltaHat.viewRow(k));
                    results.put(batchId, batchResults);
                }
            }
        });
    }

    service.shutdown();

    boolean allDone = false;
    do {
        for (Future<?> f : futures) {
            allDone = true;
            if (!f.isDone() && !f.isCancelled()) {
                allDone = false;
                break;
            }
        }
    } while (!allDone);

    for (int i = 0; i < batchIds.length; i++) {
        String batchId = batchIds[i];
        DoubleMatrix1D[] batchResults = results.get(batchId);
        for (int j = 0; j < batchResults[0].size(); j++) {
            gammastar.set(i, j, batchResults[0].get(j));
        }
        for (int j = 0; j < batchResults[1].size(); j++) {
            deltastar.set(i, j, batchResults[1].get(j));
        }
    }
}

From source file:org.apache.stratos.rest.endpoint.api.StratosApiV41Utils.java

/**
 * This method validates group aliases recursively
 *
 * @param groupsSet - the group collection in which the groups are added to
 * @param groups    - the group collection in which it traverses through
 * @throws RestAPIException// www  .j av a2  s . c  o  m
 */

private static void validateGroupsRecursively(ConcurrentHashMap<String, CartridgeGroupReferenceBean> groupsSet,
        Collection<CartridgeGroupReferenceBean> groups, boolean hasDeploymentPolicy) throws RestAPIException {

    boolean groupHasDeploymentPolicy = false;

    for (CartridgeGroupReferenceBean group : groups) {
        if (groupsSet.get(group.getAlias()) != null) {
            String message = "Cartridge group alias exists more than once: [group-alias] " + group.getAlias();
            throw new RestAPIException(message);
        }

        if (group.getDeploymentPolicy() != null) {
            if (hasDeploymentPolicy) {
                String message = "Parent group has a deployment policy. Remove deployment policy from the"
                        + " group: [group-alias] " + group.getAlias();
                throw new RestAPIException(message);
            } else {
                groupHasDeploymentPolicy = true;
            }
        } else {
            groupHasDeploymentPolicy = hasDeploymentPolicy;
        }

        if (group.getCartridges() != null) {
            validateCartridgesForDeploymentPolicy(group.getCartridges(), groupHasDeploymentPolicy);
        }

        groupsSet.put(group.getAlias(), group);

        if (group.getGroups() != null) {
            validateGroupsRecursively(groupsSet, group.getGroups(), groupHasDeploymentPolicy);
        }
    }
}

From source file:com.web.server.WebServer.java

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *//*from  w w w  . j  a va  2s .  com*/
public void run() {
    byte[] response;
    byte[] content;
    byte[] uploadData = null;
    HttpHeaderClient httpHeaderClient = null;
    InputStream istream = null;
    OutputStream ostream = null;
    HttpHeaderServer serverParam = new HttpHeaderServer();
    StringBuffer buffer = new StringBuffer();
    String value;
    char c;
    String endvalue = "\r\n\r\n";
    String urlFormEncoded;
    int responseCode;
    try {
        ////System.out.println("value=");
        istream = socket.getInputStream();
        BufferedInputStream bistr = new BufferedInputStream(istream);
        //socket.setReceiveBufferSize(10000);
        //System.out.println("value1=");
        int availbleStream;
        int totalBytRead = 0;
        int ch;
        ByteArrayOutputStream bytout = new ByteArrayOutputStream();
        ByteArrayOutputStream contentout = new ByteArrayOutputStream();
        //System.out.println(istream.available());
        int bytesRead;
        int endbytIndex = 0;
        int contentbytIndex = 0;
        boolean httpHeaderEndFound = false;
        byte[] byt;
        while ((ch = bistr.read()) != -1) {
            bytout.write(ch);
            if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                endbytIndex++;
                if (endbytIndex == endvalue.length()) {
                    byt = bytout.toByteArray();
                    value = new String(ObtainBytes(byt, 0, byt.length - 4));
                    //System.out.println(value);
                    httpHeaderClient = parseHttpHeaders(value);
                    httpHeaderEndFound = true;
                    bytout.close();
                    endbytIndex = 0;
                    if (httpHeaderClient.getContentLength() == null)
                        break;
                }
            } else {
                endbytIndex = 0;
            }
            if (httpHeaderClient != null && httpHeaderEndFound) {
                contentout.write(ch);
                contentbytIndex++;
                if (httpHeaderClient.getContentLength() != null
                        && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                    break;
                }
            }
            totalBytRead++;
        }
        /*while(totalBytRead==0){
           while((ch = bistr.read())!=-1){
              System.out.println((char)ch);
              ////System.out.println("availableStream="+availbleStream);
              bytarrayOutput.write(ch);
              totalBytRead++;
           }
        }*/
        if (totalBytRead == 0) {
            System.out.println("Since byte is 0 sock and istream os closed");
            //istream.close();
            socket.close();
            return;
        }
        //istream.read(bt,0,9999999);
        System.out.println("bytes read");
        byte[] contentByte = contentout.toByteArray();
        contentout.close();
        //System.out.println("String="+new String(bt));
        /*int index=containbytes(bt,endvalue.getBytes());
        if(index==-1)index=totalBytRead;
        value=new String(ObtainBytes(bt,0,index));*/
        System.out.println("value2=");

        ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
        HttpSessionServer session = null;
        if (httpCookies != null) {
            Iterator<String> cookieNames = httpCookies.keySet().iterator();
            for (; cookieNames.hasNext();) {
                String cookieName = cookieNames.next();
                //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                if (cookieName.equals("SERVERSESSIONID")) {
                    session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                    httpHeaderClient.setSession(session);
                    //break;
                }
            }
        }
        //System.out.println("Session="+session);
        if (session == null) {
            HttpCookie cookie = new HttpCookie();
            cookie.setKey("SERVERSESSIONID");
            cookie.setValue(UUID.randomUUID().toString());
            httpCookies.put("SERVERSESSIONID", cookie);
            session = new HttpSessionServer();
            sessionObjects.put(cookie.getValue(), session);
            httpHeaderClient.setSession(session);
        }
        if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
            ////System.out.println(new String(uploadData));
            ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
            httpHeaderClient.setParameters(paramMap);
            ////logger.info(uploadData);
        } else if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
            urlFormEncoded = new String(contentByte);
            ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
            httpHeaderClient.setParameters(paramMap);
        }
        ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
        ////System.out.println("value3=");

        ////logger.info(new String(bt));
        serverParam.setContentType("text/html");
        URLDecoder decoder = new URLDecoder();
        System.out.println("content Length= " + socket);
        responseCode = 200;
        File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
        FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
        if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
            System.out.println("In cache");
            content = (byte[]) fileContent.getContent();
        } else {
            content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                    httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
            System.out.println("content Length2= " + content);
            if (content == null) {
                //System.out.println("In caching content");
                content = obtainContent(
                        deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                if (content != null) {
                    fileContent = new FileContent();
                    fileContent.setContent(content);
                    fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                    fileContent.setLastModified(file.lastModified());
                    cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                }
            }
            ////System.out.println("value4=");

        }

        if (content == null) {
            responseCode = 404;
            content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                    + " Not Found</H1><body></html>").getBytes();
        }
        ////System.out.println("content Length3= ");
        serverParam.setContentLength("" + (content.length + 4));
        if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
            serverParam.setContentType("image/png");
        }
        ////System.out.println("value5=");

        ////System.out.println("content Length4= ");
        response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
        ////System.out.println("value6=");
        ostream = socket.getOutputStream();
        //logger.info("Response="+new String(response));
        //System.out.println("value6=");
        //logger.info("Response="+new String(response));
        ////System.out.println("content "+"Response="+new String(response));
        ostream.write(response);
        ostream.flush();
        ostream.close();
        socket.close();
    } catch (IOException e) {
        Socket socket;
        e.printStackTrace();

        //logger.error(e);
        try {
            socket = new Socket("localhost", shutdownPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
            outputStream.close();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JTable createTable(final ViewState state) {
    JTable table;/*from   w w  w  . ja  v  a  2  s.  com*/
    final ModelGraph selected = state.getSelected();
    if (selected != null) {
        final Vector<Vector<String>> rows = new Vector<Vector<String>>();
        ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>();
        Metadata staticMet = selected.getModel().getStaticMetadata();
        Metadata inheritedMet = selected.getInheritedStaticMetadata(state);
        Metadata completeMet = new Metadata();
        if (staticMet != null) {
            completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup()));
        }
        if (selected.getModel().getExtendsConfig() != null) {
            for (String configGroup : selected.getModel().getExtendsConfig()) {
                Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata()
                        .getSubMetadata(state.getCurrentMetGroup());
                for (String key : extendsMetadata.getAllKeys()) {
                    if (!completeMet.containsKey(key)) {
                        keyToGroupMap.put(key, configGroup);
                        completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key));
                    }
                }
            }
        }
        if (inheritedMet != null) {
            Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup());
            for (String key : inheritedMetadata.getAllKeys()) {
                if (!completeMet.containsKey(key)) {
                    keyToGroupMap.put(key, "__inherited__");
                    completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key));
                }
            }
        }
        List<String> keys = completeMet.getAllKeys();
        Collections.sort(keys);
        for (String key : keys) {
            if (key.endsWith("/envReplace")) {
                continue;
            }
            String values = StringUtils.join(completeMet.getAllMetadata(key), ",");
            Vector<String> row = new Vector<String>();
            row.add(keyToGroupMap.get(key));
            row.add(key);
            row.add(values);
            row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace"))));
            rows.add(row);
        }
        table = new JTable();// rows, new Vector<String>(Arrays.asList(new
                             // String[] { "key", "values", "envReplace" })));
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                switch (col) {
                case 0:
                    return "group";
                case 1:
                    return "key";
                case 2:
                    return "values";
                case 3:
                    return "envReplace";
                default:
                    return null;
                }
            }

            public int getRowCount() {
                return rows.size() + 1;
            }

            public int getColumnCount() {
                return 4;
            }

            public Object getValueAt(int row, int col) {
                if (row >= rows.size()) {
                    return null;
                }
                String value = rows.get(row).get(col);
                if (value == null && col == 3) {
                    return "false";
                }
                if (value == null && col == 0) {
                    return "__local__";
                }
                return value;
            }

            public boolean isCellEditable(int row, int col) {
                if (row >= rows.size()) {
                    return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup());
                }
                if (col == 0) {
                    return false;
                }
                String key = rows.get(row).get(1);
                return key == null || (selected.getModel().getStaticMetadata() != null
                        && selected.getModel().getStaticMetadata().containsKey(getKey(key, state)));
            }

            public void setValueAt(Object value, int row, int col) {
                if (row >= rows.size()) {
                    Vector<String> newRow = new Vector<String>(
                            Arrays.asList(new String[] { null, null, null, null }));
                    newRow.add(col, (String) value);
                    rows.add(newRow);
                } else {
                    Vector<String> rowValues = rows.get(row);
                    rowValues.add(col, (String) value);
                    rowValues.remove(col + 1);
                }
                this.fireTableCellUpdated(row, col);
            }

        });
        MyTableListener tableListener = new MyTableListener(state);
        table.getModel().addTableModelListener(tableListener);
        table.getSelectionModel().addListSelectionListener(tableListener);
    } else {
        table = new JTable(new Vector<Vector<String>>(),
                new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" })));
    }

    // table.setFillsViewportHeight(true);
    table.setSelectionBackground(Color.cyan);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableCellRenderer cellRenderer = new TableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel field = new JLabel((String) value);
            if (column == 0) {
                field.setForeground(Color.gray);
            } else {
                if (isSelected) {
                    field.setBorder(new EtchedBorder(1));
                }
                if (table.isCellEditable(row, 1)) {
                    field.setForeground(Color.black);
                } else {
                    field.setForeground(Color.gray);
                }
            }
            return field;
        }

    };
    TableColumn groupCol = table.getColumnModel().getColumn(0);
    groupCol.setPreferredWidth(75);
    groupCol.setCellRenderer(cellRenderer);
    TableColumn keyCol = table.getColumnModel().getColumn(1);
    keyCol.setPreferredWidth(200);
    keyCol.setCellRenderer(cellRenderer);
    TableColumn valuesCol = table.getColumnModel().getColumn(2);
    valuesCol.setPreferredWidth(300);
    valuesCol.setCellRenderer(cellRenderer);
    TableColumn envReplaceCol = table.getColumnModel().getColumn(3);
    envReplaceCol.setPreferredWidth(75);
    envReplaceCol.setCellRenderer(cellRenderer);

    table.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) {
                int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition());
                String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state);
                Metadata staticMet = state.getSelected().getModel().getStaticMetadata();
                override.setVisible(staticMet == null || !staticMet.containsKey(key));
                delete.setVisible(staticMet != null && staticMet.containsKey(key));
                tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    return table;
}

From source file:com.web.server.WebServer.java

/**
 * This method obtains the url parameters
 * @param url//from  www.  j a  va 2 s.  c o  m
 * @param params
 * @return string
 */
public String ObtainUrlAndParams(String url, ConcurrentHashMap params) {

    URLDecoder decoder = new URLDecoder();
    url = decoder.decode(url);
    if (url.indexOf("?") > -1) {
        String paramaters = url.substring(url.indexOf("?") + 1);
        StringTokenizer paramGroup = new StringTokenizer(paramaters, "&");

        while (paramGroup.hasMoreTokens()) {

            StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "=");
            String param = null;
            if (value.hasMoreTokens()) {
                param = value.nextToken();
            }
            String paramValue = null;
            if (value.hasMoreTokens()) {
                paramValue = value.nextToken();
            }
            if (param != null && paramValue != null) {
                if (params.get(param) != null) {
                    if (params.get(param) instanceof String[]) {
                        String[] parameters = (String[]) params.get(param);
                        String[] paramValues = new String[parameters.length + 1];
                        for (int paramcount = 0; paramcount < parameters.length; paramcount++) {
                            paramValues[paramcount] = parameters[paramcount];
                        }
                        paramValues[parameters.length] = paramValue;
                        params.put(param, paramValues);
                    } else if (params.get(param) instanceof String) {
                        String[] paramValues = new String[2];
                        paramValues[0] = (String) params.get(param);
                        paramValues[1] = paramValue;
                        params.put(param, paramValues);
                    }
                } else {
                    params.put(param, paramValue);
                }
            }
        }
    }
    if (url.indexOf("?") != -1) {
        return url.substring(0, url.indexOf("?"));
    }
    return url;
}