Example usage for java.util LinkedList size

List of usage examples for java.util LinkedList size

Introduction

In this page you can find the example usage for java.util LinkedList size.

Prototype

int size

To view the source code for java.util LinkedList size.

Click Source Link

Usage

From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java

private void reorder(int inicio, int fin) {

    boolean sentido = inicio < fin;

    LinkedList<Object> aSubir = new LinkedList<Object>();
    LinkedList<Object> resultado = new LinkedList<Object>();

    for (Object o : right.getSelectedValues()) {
        aSubir.add(o);//  w  w  w . ja v a  2s  .c om
    }

    final DefaultListModel defaultListModel = (DefaultListModel) right.getModel();

    if (log.isTraceEnabled()) {
        log.trace("Elementos seleccionados:");
        for (Object o : aSubir) {
            log.trace(o + " " + o.getClass());
        }
    }

    for (int i = inicio; (sentido ? i <= fin : fin <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = defaultListModel.get(i);
        if (aSubir.contains(o) && i != inicio) {
            Object siguiente = resultado.pollLast();
            log.trace("Cambiamos " + o + " por " + siguiente);
            resultado.add(o);
            resultado.add(siguiente);
        } else {
            log.trace("Aadimos " + o);
            resultado.add(o);
        }
    }

    ((DefaultListModel) right.getModel()).removeAllElements();
    log.trace("Nueva lista: ");

    int inicio2 = (sentido ? 0 : resultado.size() - 1);
    int fin2 = (sentido ? resultado.size() - 1 : 0);
    for (int i = inicio2; (sentido ? i <= fin2 : fin2 <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = resultado.get(i);
        log.trace("Nueva lista >" + o);
        ((DefaultListModel) right.getModel()).addElement(o);
    }

    int seleccion[] = new int[aSubir.size()];
    int k = 0;
    for (Integer i = 0; i < right.getModel().getSize(); i++) {
        if (aSubir.contains(right.getModel().getElementAt(i))) {
            seleccion[k++] = i;
        }
    }

    right.setSelectedIndices(seleccion);

    right.updateUI();
}

From source file:com.github.vanroy.springdata.jest.JestElasticsearchTemplateTests.java

@Test
public void shouldReturnObjectsForGivenIdsUsingMultiGet() {
    // given/* w  ww. jav a2 s  . c om*/
    List<IndexQuery> indexQueries;
    // first document
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message")
            .version(System.currentTimeMillis()).build();

    // second document
    String documentId2 = randomNumeric(5);
    SampleEntity sampleEntity2 = SampleEntity.builder().id(documentId2).message("some message")
            .version(System.currentTimeMillis()).build();

    indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2));

    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(SampleEntity.class);

    // when
    SearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2)).build();
    LinkedList<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class);
    // then
    assertThat(sampleEntities.size(), is(equalTo(2)));
    assertEquals(sampleEntities.get(0), sampleEntity1);
    assertEquals(sampleEntities.get(1), sampleEntity2);
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

/**
 * Sorts certificate chain from root to leaf.
 *
 * This method sorts an array of certificates (e.g. from a PKCS #7
 * data) that represents a certificate chain from root to leaf
 * according to the subject DNs and issuer DNs.
 *
 * The input array is a set of certificates that are part of a
 * chain but not in specific order./* w ww.  j a v  a 2 s .  com*/
 *
 * The result is a new array that contains the certificate chain
 * sorted from root to leaf. The input array is unchanged.
 *
 * @param certs input array of certificates
 * @return new array containing sorted certificates
 */
public static java.security.cert.X509Certificate[] sortCertificateChain(
        java.security.cert.X509Certificate[] certs) throws Exception {

    // lookup map: subject DN -> cert
    Map<String, java.security.cert.X509Certificate> certMap = new LinkedHashMap<>();

    // hierarchy map: subject DN -> issuer DN
    Map<String, String> parentMap = new HashMap<>();

    // reverse hierarchy map: issuer DN -> subject DN
    Map<String, String> childMap = new HashMap<>();

    // build maps
    for (java.security.cert.X509Certificate cert : certs) {

        String subjectDN = cert.getSubjectDN().toString();
        String issuerDN = cert.getIssuerDN().toString();

        if (certMap.containsKey(subjectDN)) {
            throw new Exception("Duplicate certificate: " + subjectDN);
        }

        certMap.put(subjectDN, cert);

        // ignore self-signed certificate
        if (subjectDN.equals(issuerDN))
            continue;

        if (childMap.containsKey(issuerDN)) {
            throw new Exception("Branched chain: " + issuerDN);
        }

        parentMap.put(subjectDN, issuerDN);
        childMap.put(issuerDN, subjectDN);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Certificates:");
        for (String subjectDN : certMap.keySet()) {
            logger.debug(" - " + subjectDN);

            String parent = parentMap.get(subjectDN);
            if (parent != null)
                logger.debug("   parent: " + parent);

            String child = childMap.get(subjectDN);
            if (child != null)
                logger.debug("   child: " + child);
        }
    }

    // find leaf cert
    List<String> leafCerts = new ArrayList<>();

    for (String subjectDN : certMap.keySet()) {

        // if cert has a child, skip
        if (childMap.containsKey(subjectDN))
            continue;

        // found leaf cert
        leafCerts.add(subjectDN);
    }

    if (leafCerts.isEmpty()) {
        throw new Exception("Unable to find leaf certificate");
    }

    if (leafCerts.size() > 1) {
        StringBuilder sb = new StringBuilder();
        for (String subjectDN : leafCerts) {
            if (sb.length() > 0)
                sb.append(", ");
            sb.append("[" + subjectDN + "]");
        }
        throw new Exception("Multiple leaf certificates: " + sb);
    }

    // build sorted chain
    LinkedList<java.security.cert.X509Certificate> chain = new LinkedList<>();

    // start from leaf
    String current = leafCerts.get(0);

    while (current != null) {

        java.security.cert.X509Certificate cert = certMap.get(current);

        if (cert == null) {
            // incomplete chain
            break;
        }

        // add to the beginning of chain
        chain.addFirst(cert);

        // follow parent to root
        current = parentMap.get(current);
    }

    return chain.toArray(new java.security.cert.X509Certificate[chain.size()]);
}

From source file:com.stimulus.archiva.search.StandardSearch.java

protected Searcher getVolumeSearchers() throws MessageSearchException {

    logger.debug("getVolumeSearchers()");
    boolean searcherPresent = false;
    Hashtable<String, String> remoteServers = new Hashtable<String, String>();
    List<Volume> volumes = Config.getConfig().getVolumes().getVolumes();
    LinkedList<Searchable> searchers = new LinkedList<Searchable>();
    Iterator<Volume> vl = volumes.iterator();
    logger.debug("searching for suitable searchers");
    while (vl.hasNext()) {
        Volume volume = (Volume) vl.next();
        logger.debug("should search volume? {" + volume + "}");
        try {//from w  w  w. j  a  va2  s.c  o  m
            Searchable volsearcher;
            if (shouldSearch(volume)) {
                try {
                    volsearcher = new IndexSearcher(volume.getIndexPath());
                    logger.debug("adding volume to search {indexpath='" + volume.getIndexPath() + "'}");
                    searchers.add(volsearcher);
                    searcherPresent = true;
                } catch (Exception e) {
                    logger.error("failed to volume to search{" + volume + "}: " + e.getMessage(), e);
                }
            } else {
                logger.debug("deliberately not searching inside volume {" + volume.getIndexPath() + "}");
            }
        } catch (Exception io) {
            logger.error("failed to open index for search {" + volume + "}.", io);
        }

    }

    if (!searcherPresent)
        return null;

    for (String remotePath : remoteServers.values()) {
        try {
            Searchable volsearcher = (Searchable) Naming.lookup(remotePath);
            searchers.add(volsearcher);
        } catch (Exception e) {
            logger.error("failed to add volume searcher", e);
        }
    }
    Searchable[] searcherarraytype = new Searchable[searchers.size()];
    Searchable[] allsearchers = (Searchable[]) (searchers.toArray(searcherarraytype));

    Searcher searcher;
    try {
        searcher = new ParallelMultiSearcher(allsearchers);
    } catch (IOException io) {
        throw new MessageSearchException("failed to open/create one or more index searchers", logger);
    }
    return searcher;
}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Lists changes. Next page token is the ID of the last change listed.
 *///from  ww w .  j  a  va  2  s  .com
@VisibleForTesting
Response listChanges(String projectId, String zoneName, String query) {
    Map<String, Object> options = OptionParsers.parseListChangesOptions(query);
    Response response = checkListOptions(options);
    if (response != null) {
        return response;
    }
    ZoneContainer zoneContainer = findZone(projectId, zoneName);
    if (zoneContainer == null) {
        return Error.NOT_FOUND.response(
                String.format("The 'parameters.managedZone' resource named '%s' does not exist", zoneName));
    }
    // take a sorted snapshot of the current change list
    NavigableMap<Integer, Change> changes = new TreeMap<>();
    for (Change c : zoneContainer.changes()) {
        if (c.getId() != null) {
            changes.put(Integer.valueOf(c.getId()), c);
        }
    }
    String[] fields = (String[]) options.get("fields");
    String sortOrder = (String) options.get("sortOrder");
    String pageToken = (String) options.get("pageToken");
    Integer maxResults = options.get("maxResults") == null ? null
            : Integer.valueOf((String) options.get("maxResults"));
    // as the only supported field is change sequence, we are not reading sortBy
    NavigableSet<Integer> keys;
    if ("descending".equals(sortOrder)) {
        keys = changes.descendingKeySet();
    } else {
        keys = changes.navigableKeySet();
    }
    Integer from = null;
    try {
        from = Integer.valueOf(pageToken);
    } catch (NumberFormatException ex) {
        // ignore page token
    }
    keys = from != null ? keys.tailSet(from, false) : keys;
    NavigableMap<Integer, Change> fragment = from != null && changes.containsKey(from)
            ? changes.tailMap(from, false)
            : changes;
    boolean sizeReached = false;
    boolean hasMorePages = false;
    LinkedList<String> serializedResults = new LinkedList<>();
    String lastChangeId = null;
    for (Integer key : keys) {
        Change change = fragment.get(key);
        if (sizeReached) {
            // we do not add this, just note that there would be more and there should be a token
            hasMorePages = true;
            break;
        } else {
            lastChangeId = change.getId();
            try {
                serializedResults.addLast(jsonFactory.toString(OptionParsers.extractFields(change, fields)));
            } catch (IOException e) {
                return Error.INTERNAL_ERROR.response(
                        String.format("Error when serializing change %s in managed zone %s in project %s",
                                lastChangeId, zoneName, projectId));
            }
        }
        sizeReached = maxResults != null && maxResults.equals(serializedResults.size());
    }
    boolean includePageToken = hasMorePages
            && (fields == null || Arrays.asList(fields).contains("nextPageToken"));
    return toListResponse(serializedResults, "changes", lastChangeId, includePageToken);
}

From source file:com.att.nsa.cambria.service.impl.MMServiceImpl.java

private void pushEventsWithTransaction(DMaaPContext ctx, InputStream inputStream, final String topic,
        final String partitionKey, final String requestTime, final boolean chunked, final String mediaType)
        throws ConfigDbException, AccessDeniedException, TopicExistsException, IOException,
        CambriaApiException {/*from  w  w  w  . j  av  a  2 s .  co  m*/

    final MetricsSet metricsSet = ctx.getConfigReader().getfMetrics();

    // setup the event set
    final CambriaEventSet events = new CambriaEventSet(mediaType, inputStream, chunked, partitionKey);

    // start processing, building a batch to push to the backend
    final long startMs = System.currentTimeMillis();
    long count = 0;
    long maxEventBatch = 1024 * 16;
    String evenlen = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, BATCH_LENGTH);
    if (null != evenlen)
        maxEventBatch = Long.parseLong(evenlen);

    final LinkedList<Publisher.message> batch = new LinkedList<Publisher.message>();
    final ArrayList<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>();

    Publisher.message m = null;
    int messageSequence = 1;
    Long batchId = 1L;
    final boolean transactionEnabled = true;
    int publishBatchCount = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");

    // LOG.warn("Batch Start Id: " +
    // Utils.getFromattedBatchSequenceId(batchId));
    try {
        // for each message...
        batchId = DMaaPContext.getBatchID();

        String responseTransactionId = null;

        while ((m = events.next()) != null) {

            // LOG.warn("Batch Start Id: " +
            // Utils.getFromattedBatchSequenceId(batchId));

            addTransactionDetailsToMessage(m, topic, ctx.getRequest(), requestTime, messageSequence, batchId,
                    transactionEnabled);
            messageSequence++;

            // add the message to the batch
            batch.add(m);

            responseTransactionId = m.getLogDetails().getTransactionId();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", m.getMessage());
            jsonObject.put("transactionId", responseTransactionId);
            final KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, m.getKey(),
                    jsonObject.toString());
            kms.add(data);

            // check if the batch is full
            final int sizeNow = batch.size();
            if (sizeNow >= maxEventBatch) {
                String startTime = sdf.format(new Date());
                LOG.info("Batch Start Details:[serverIp=" + ctx.getRequest().getLocalAddr() + ",Batch Start Id="
                        + batchId + "]");
                try {
                    ctx.getConfigReader().getfPublisher().sendBatchMessage(topic, kms);
                    // transactionLogs(batch);
                    for (message msg : batch) {
                        LogDetails logDetails = msg.getLogDetails();
                        LOG.info("Publisher Log Details : " + logDetails.getPublisherLogDetails());
                    }
                } catch (Exception excp) {

                    int status = HttpStatus.SC_NOT_FOUND;
                    String errorMsg = null;
                    if (excp instanceof CambriaApiException) {
                        status = ((CambriaApiException) excp).getStatus();
                        JSONTokener jsonTokener = new JSONTokener(((CambriaApiException) excp).getBody());
                        JSONObject errObject = new JSONObject(jsonTokener);
                        errorMsg = (String) errObject.get("message");
                    }
                    ErrorResponse errRes = new ErrorResponse(status,
                            DMaaPResponseCode.PARTIAL_PUBLISH_MSGS.getResponseCode(),
                            "Transaction-" + errorMessages.getPublishMsgError() + ":" + topic + "."
                                    + errorMessages.getPublishMsgCount() + count + "." + errorMsg,
                            null, Utils.getFormattedDate(new Date()), topic,
                            Utils.getUserApiKey(ctx.getRequest()), ctx.getRequest().getRemoteHost(), null,
                            null);
                    LOG.info(errRes.toString());
                    throw new CambriaApiException(errRes);
                }
                kms.clear();
                batch.clear();
                metricsSet.publishTick(sizeNow);
                publishBatchCount = sizeNow;
                count += sizeNow;
                // batchId++;
                String endTime = sdf.format(new Date());
                LOG.info("Batch End Details:[serverIp=" + ctx.getRequest().getLocalAddr() + ",Batch End Id="
                        + batchId + ",Batch Total=" + publishBatchCount + ",Batch Start Time=" + startTime
                        + ",Batch End Time=" + endTime + "]");
                batchId = DMaaPContext.getBatchID();
            }
        }

        // send the pending batch
        final int sizeNow = batch.size();
        if (sizeNow > 0) {
            String startTime = sdf.format(new Date());
            LOG.info("Batch Start Details:[serverIp=" + ctx.getRequest().getLocalAddr() + ",Batch Start Id="
                    + batchId + "]");
            try {
                ctx.getConfigReader().getfPublisher().sendBatchMessage(topic, kms);
                // transactionLogs(batch);
                for (message msg : batch) {
                    LogDetails logDetails = msg.getLogDetails();
                    LOG.info("Publisher Log Details : " + logDetails.getPublisherLogDetails());
                }
            } catch (Exception excp) {
                int status = HttpStatus.SC_NOT_FOUND;
                String errorMsg = null;
                if (excp instanceof CambriaApiException) {
                    status = ((CambriaApiException) excp).getStatus();
                    JSONTokener jsonTokener = new JSONTokener(((CambriaApiException) excp).getBody());
                    JSONObject errObject = new JSONObject(jsonTokener);
                    errorMsg = (String) errObject.get("message");
                }

                ErrorResponse errRes = new ErrorResponse(status,
                        DMaaPResponseCode.PARTIAL_PUBLISH_MSGS.getResponseCode(),
                        "Transaction-" + errorMessages.getPublishMsgError() + ":" + topic + "."
                                + errorMessages.getPublishMsgCount() + count + "." + errorMsg,
                        null, Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(ctx.getRequest()),
                        ctx.getRequest().getRemoteHost(), null, null);
                LOG.info(errRes.toString());
                throw new CambriaApiException(errRes);
            }
            kms.clear();
            metricsSet.publishTick(sizeNow);
            count += sizeNow;
            // batchId++;
            String endTime = sdf.format(new Date());
            publishBatchCount = sizeNow;
            LOG.info("Batch End Details:[serverIp=" + ctx.getRequest().getLocalAddr() + ",Batch End Id="
                    + batchId + ",Batch Total=" + publishBatchCount + ",Batch Start Time=" + startTime
                    + ",Batch End Time=" + endTime + "]");
        }

        final long endMs = System.currentTimeMillis();
        final long totalMs = endMs - startMs;

        LOG.info("Published " + count + " msgs in " + totalMs + "ms for topic " + topic);

        // build a response
        final JSONObject response = new JSONObject();
        response.put("count", count);
        response.put("serverTimeMs", totalMs);

    } catch (Exception excp) {
        int status = HttpStatus.SC_NOT_FOUND;
        String errorMsg = null;
        if (excp instanceof CambriaApiException) {
            status = ((CambriaApiException) excp).getStatus();
            JSONTokener jsonTokener = new JSONTokener(((CambriaApiException) excp).getBody());
            JSONObject errObject = new JSONObject(jsonTokener);
            errorMsg = (String) errObject.get("message");
        }

        ErrorResponse errRes = new ErrorResponse(status,
                DMaaPResponseCode.PARTIAL_PUBLISH_MSGS.getResponseCode(),
                "Transaction-" + errorMessages.getPublishMsgError() + ":" + topic + "."
                        + errorMessages.getPublishMsgCount() + count + "." + errorMsg,
                null, Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(ctx.getRequest()),
                ctx.getRequest().getRemoteHost(), null, null);
        LOG.info(errRes.toString());
        throw new CambriaApiException(errRes);
    }
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * Parses the XML Document passed into the application.
 * /*  w w  w. j ava  2s . co  m*/
 * @param args - the fully-qualified name of the test
 *          script document.
 * @return - true if the document parsed successfully, 
 *          false otherwise.
 */
protected boolean parseAndStart() {
    //String ts = testScriptFiles.getFirst(); 
    File f = new File(activeTestScriptFile);
    if (f != null) {
        logger.info(PC2LogCategory.Parser, subCat, "Using input document " + activeTestScriptFile);

        TSParser tsp = new TSParser(true);
        try {
            doc = tsp.parse(activeTestScriptFile);
            logPackage();
            logger.info(PC2LogCategory.Parser, subCat,
                    "Using input document " + activeTestScriptFile + " v." + doc.getVersion());

            Stacks.logStackSocketInformation();
            ss.setDynamicPlatformSettings(doc.getProperties());
            ss.logSettings();

            // Now see if we are running a test for an UE and if so
            // See if we should auto provision the device?
            ProvisioningData pd = autoProvision(doc.getName());
            if (pd != null) {
                String macAddr = autoGenerate(pd);
                if (macAddr != null) {
                    // doc.setAutoProv(pd);
                    logger.info(PC2LogCategory.PCSim2, subCat,
                            "Updating the global registrar's that the DUT is rebooting");

                    ProvListener pl = new ProvListener(pd);
                    if (pl != null) {
                        logger.debug(PC2LogCategory.PCSim2, subCat,
                                "Starting the provisioning listener operation.");
                        autoProvisioned = pl.run();
                        if (!autoProvisioned) {
                            logger.error(PC2LogCategory.PCSim2, subCat,
                                    "Auto provisioning did not occur as expected, test is terminating.");
                            provDB.clearIssuedData(macAddr);
                            return false;
                        } else {
                            Properties dut = SystemSettings.getSettings(SettingConstants.DUT);
                            String pui = dut.getProperty(SettingConstants.PUI);
                            if (pui != null)
                                Stacks.generateAutoRebootEvent(pui);
                            String pui2 = dut.getProperty(SettingConstants.PUI2);
                            if (pui2 != null)
                                Stacks.generateAutoRebootEvent(pui2);
                            logger.info(PC2LogCategory.PCSim2, subCat,
                                    "Test execution pausing while resetting the DUT.");
                            Thread.sleep(5000);
                            logger.info(PC2LogCategory.PCSim2, subCat, "Pause complete.");
                        }
                    }
                } else {
                    logger.info(PC2LogCategory.PCSim2, subCat,
                            "Auto generate didn't return an updated data file for provisioning.");
                }
            } else {
                logger.info(PC2LogCategory.PCSim2, subCat,
                        "Auto provisioning did not return a data file for the device.");
            }

            LinkedList<FSM> fsms = doc.getFsms();
            // Initialize the settings that can be overwritten from
            // within the document 
            setExtensions(fsms);
            if (doc.getInspector())
                ss.enableInspector();

            for (int i = 0; i < fsms.size(); i++) {
                FSM fsm = fsms.get(i);
                PC2Models testModel = null;
                String modelName = fsm.getModel().getName();
                if (modelName.equalsIgnoreCase("session")) {
                    testModel = new Session(fsm);
                    if (testModel != null)
                        testModel.init();
                    try {
                        fsm.getNetworkElements().certify();
                    } catch (PC2Exception e) {

                    }
                } else if (modelName.equalsIgnoreCase(MsgRef.STUN_MSG_TYPE)) {
                    testModel = new Stun(fsm);
                    if (testModel != null)
                        testModel.init();
                    //if (!fsm.getNetworkElements().certify())
                    //   return false;
                } else if (modelName.equalsIgnoreCase("registrar")) {
                    Properties dut = SystemSettings.getSettings("DUT");
                    String pui = dut.getProperty(SettingConstants.PUI);
                    Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
                    String destIP = platform.getProperty(SettingConstants.IP);
                    if (pui != null) {
                        testModel = new Registrar(fsm, pui, destIP);
                        if (testModel != null)
                            testModel.init();
                        try {
                            fsm.getNetworkElements().certify();
                        } catch (PC2Exception e) {

                        }
                    } else
                        return false;
                }
                if (modelName.equalsIgnoreCase("register")) {
                    testModel = new Register(fsm);
                    if (testModel != null)
                        testModel.init();
                    try {
                        fsm.getNetworkElements().certify();
                    } catch (PC2Exception e) {

                    }
                }

                if (testModel != null) {
                    testModel.start();
                    activeModels.add(testModel);
                }
            }
            return true;
        } catch (PC2XMLException pe) {
            String err = "\n** Parsing error in file \n    " + pe.getFileName() + " at line "
                    + pe.getLineNumber();
            if (pe.getSystemId() != null) {
                err += ", uri " + pe.getSystemId();
            }
            if (pe.getPublicId() != null) {
                err += ", public " + pe.getPublicId();
            }
            err += "\n";

            logger.fatal(PC2LogCategory.Parser, subCat, err, pe);
        } catch (SAXParseException spe) {
            String err = "\n** Parsing error in file \n    " + activeTestScriptFile + " at line "
                    + spe.getLineNumber();
            if (spe.getSystemId() != null) {
                err += ", uri " + spe.getSystemId();
            }
            if (spe.getPublicId() != null) {
                err += ", public " + spe.getPublicId();
            }
            err += "\n";

            logger.fatal(PC2LogCategory.Parser, subCat, err, spe);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return false;
}

From source file:cnedu.ustcjd.widget.MultiSlider.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!mIsUserSeekable || !isEnabled()) {
        return false;
    }/*from  w ww. ja  v a  2 s  .  c o  m*/
    final int xx = Math.round(event.getX());
    final int yy = Math.round(event.getY());

    int pointerIdx = event.getActionIndex();

    Thumb currThumb = null;
    if (event.getActionMasked() == MotionEvent.ACTION_DOWN
            || event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
        LinkedList<Thumb> closestOnes = getClosestThumb((int) event.getX(pointerIdx));

        if (isInScrollingContainer() && mDraggingThumbs.size() == 0 && exactTouched != null && pointerIdx > 0) {
            //we have been here before => we want to use the bar
            Thumb prevThumb = exactTouched.getFirst();
            onStartTrackingTouch(prevThumb);
            exactTouched = null;
        }

        if (closestOnes != null && !closestOnes.isEmpty()) {
            if (closestOnes.size() == 1) {
                currThumb = closestOnes.getFirst();
                if (isInScrollingContainer() && mDraggingThumbs.size() == 0) {
                    exactTouched = closestOnes;
                }
            } else {
                //we have more than one thumb at the same place and we touched there
                exactTouched = closestOnes;
            }
        }
    } else if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
        if (exactTouched != null && !exactTouched.isEmpty()) {
            currThumb = getMostMovableThumb(event);
            //check if move actually changed value
            // if (currThumb == null) return false;
        } else if (mDraggingThumbs.size() > pointerIdx) {
            currThumb = mDraggingThumbs.get(pointerIdx);
        }
    } else if (event.getActionMasked() == MotionEvent.ACTION_UP
            || event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) {
        if (mDraggingThumbs.size() > pointerIdx) {
            currThumb = mDraggingThumbs.get(pointerIdx);
        } //else we had a candidate but was never tracked
        else if (exactTouched != null && exactTouched.size() > 0) {
            currThumb = getMostMovableThumb(event);
            exactTouched = null;
        }
    }
    //        else {
    //            LinkedList<Thumb> closestOnes = getClosestThumb((int) event.getX());
    //            currThumb = closestOnes.getFirst();
    //        }

    switch (event.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_POINTER_DOWN:
        if (isInScrollingContainer() && mDraggingThumbs.size() == 0) {
            mTouchDownX = event.getX(pointerIdx);
        } else {
            onStartTrackingTouch(currThumb);
            setThumbValue(currThumb, getValue(event, currThumb), true);
            setHotspot(xx, yy, currThumb);
        }
        break;
    //with move we dont have pointer action so set them all
    case MotionEvent.ACTION_MOVE:
        if (mDraggingThumbs.contains(currThumb)) {
            //need the index
            for (int i = 0; i < mDraggingThumbs.size(); i++) {
                if (mDraggingThumbs.get(i) != null && mDraggingThumbs.get(i).getThumb() != null) {
                    invalidate(mDraggingThumbs.get(i).getThumb().getBounds());
                }
                setThumbValue(mDraggingThumbs.get(i), getValue(event, i, mDraggingThumbs.get(i)), true);

            }
            setHotspot(xx, yy, currThumb);
        } else {
            final float x = event.getX(pointerIdx);
            if (Math.abs(x - mTouchDownX) > mScaledTouchSlop) {
                onStartTrackingTouch(currThumb);
                exactTouched = null;
                setThumbValue(currThumb, getValue(event, currThumb), true);
                setHotspot(xx, yy, currThumb);
            }
        }

        break;

    case MotionEvent.ACTION_UP:
        setPressed(false);
        //there are other pointers left
    case MotionEvent.ACTION_POINTER_UP:
        if (currThumb != null) {
            boolean toUnPress = false;
            if (!isPressed()) {
                setPressed(true);
                toUnPress = true;
            }
            setThumbValue(currThumb, getValue(event, currThumb), true);
            setHotspot(xx, yy, currThumb);
            onStopTrackingTouch(currThumb);
            if (toUnPress) {
                setPressed(false);
            }
        } else {
            //                    currThumb = getClosestThumb(newValue);
            //                    // Touch up when we never crossed the touch slop threshold should
            //                    // be interpreted as a tap-seek to that location.
            //                    onStartTrackingTouch(currThumb);
            //                    setThumbValue(currThumb, newValue, true);
            //                    onStopTrackingTouch(currThumb);
        }
        // ProgressBar doesn't know to repaint the thumb drawable
        // in its inactive state when the touch stops (because the
        // value has not apparently changed)
        invalidate();
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mDraggingThumbs != null) {
            onStopTrackingTouch();
            setPressed(false);
        }
        invalidate(); // see above explanation
        break;
    }
    return true;
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java

/** Get the file classpath of the context.
 * This method makes a best effort to return a complete file
 * classpath for the context.//from  w  w w .ja va2 s  .  c o m
 * It is obtained by walking the classloader hierarchy and looking for
 * URLClassLoaders.  The system property java.class.path is also checked for
 * file elements not already found in the loader hierarchy.
 * @return Path of files and directories for loading classes.
 * @exception IllegalStateException HttpContext.initClassLoader
 * has not been called.
 */
public String getFileClassPath() throws IllegalStateException {

    ClassLoader loader = getClassLoader();
    if (loader == null)
        throw new IllegalStateException("Context classloader not initialized");

    LinkedList paths = new LinkedList();
    LinkedList loaders = new LinkedList();

    // Walk the loader hierarchy
    while (loader != null) {
        loaders.add(0, loader);
        loader = loader.getParent();
    }

    // Try to handle java2compliant modes
    loader = getClassLoader();
    if (loader instanceof ContextLoader && !((ContextLoader) loader).isJava2Compliant()) {
        loaders.remove(loader);
        loaders.add(0, loader);
    }

    for (int i = 0; i < loaders.size(); i++) {
        loader = (ClassLoader) loaders.get(i);

        if (log.isDebugEnabled())
            log.debug("extract paths from " + loader);
        if (loader instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) loader).getURLs();
            for (int j = 0; urls != null && j < urls.length; j++) {
                try {
                    Resource path = Resource.newResource(urls[j]);
                    if (log.isTraceEnabled())
                        log.trace("path " + path);
                    File file = path.getFile();
                    if (file != null)
                        paths.add(file.getAbsolutePath());
                } catch (Exception e) {
                    LogSupport.ignore(log, e);
                }
            }
        }
    }

    // Add the system classpath elements from property.
    String jcp = System.getProperty("java.class.path");
    if (jcp != null) {
        StringTokenizer tok = new StringTokenizer(jcp, File.pathSeparator);
        while (tok.hasMoreTokens()) {
            String path = tok.nextToken();
            if (!paths.contains(path)) {
                if (log.isTraceEnabled())
                    log.trace("PATH=" + path);
                paths.add(path);
            } else if (log.isTraceEnabled())
                log.trace("done=" + path);
        }
    }

    StringBuffer buf = new StringBuffer();
    Iterator iter = paths.iterator();
    while (iter.hasNext()) {
        if (buf.length() > 0)
            buf.append(File.pathSeparator);
        buf.append(iter.next().toString());
    }

    if (log.isDebugEnabled())
        log.debug("fileClassPath=" + buf);
    return buf.toString();
}

From source file:com.commander4j.thread.InboundMessageThread.java

public void run() {
    logger.debug("InboundMessageThread running");
    Boolean dbconnected = false;//from w  w  w.  jav  a  2 s. c  om

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {
        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);
    } else {
        dbconnected = true;
    }

    if (dbconnected) {
        JDBInterfaceLog il = new JDBInterfaceLog(getHostID(), getSessionID());
        JeMail mail = new JeMail(getHostID(), getSessionID());
        JDBInterface inter = new JDBInterface(getHostID(), getSessionID());
        IncommingMaterialDefinition imd = new IncommingMaterialDefinition(getHostID(), getSessionID());
        IncommingProcessOrderStatusChange iposc = new IncommingProcessOrderStatusChange(getHostID(),
                getSessionID());
        IncommingProductionDeclarationConfirmation ipd = new IncommingProductionDeclarationConfirmation(
                getHostID(), getSessionID());
        IncommingProcessOrder ipo = new IncommingProcessOrder(getHostID(), getSessionID());
        IncommingLocation ilocn = new IncommingLocation(getHostID(), getSessionID());
        IncommingPalletStatusChange ipsc = new IncommingPalletStatusChange(getHostID(), getSessionID());
        IncommingPalletMove ipmv = new IncommingPalletMove(getHostID(), getSessionID());
        IncommingBatchStatusChange bsc = new IncommingBatchStatusChange(getHostID(), getSessionID());
        IncommingJourney ij = new IncommingJourney(getHostID(), getSessionID());
        IncommingInspectionResult iirslt = new IncommingInspectionResult(getHostID(), getSessionID());
        IncommingDespatchConfirmation idc = new IncommingDespatchConfirmation(getHostID(), getSessionID());
        IncommingQMInspectionRequest iireq = new IncommingQMInspectionRequest(getHostID(), getSessionID());
        IncommingMaterialAutoMove imam = new IncommingMaterialAutoMove(getHostID(), getSessionID());
        GenericMessageHeader gmh = new GenericMessageHeader();
        LinkedList<String> filenames = new LinkedList<String>();
        BasicFileAttributes attrs;

        while (true) {

            com.commander4j.util.JWait.milliSec(100);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            if (InboundMessageCollectionThread.recoveringFiles == false) {

                dir = new File(inputPath);

                chld = dir.listFiles((FileFilter) FileFileFilter.FILE);

                if (chld == null) {
                    allDone = true;
                } else {
                    Arrays.sort(chld, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
                    filenames.clear();

                    for (int i = 0; (i < chld.length) & (i < maxfiles); i++) {
                        fileName = chld[i].getName();
                        try {
                            attrs = Files.readAttributes(chld[i].getAbsoluteFile().toPath(),
                                    BasicFileAttributes.class);

                            if (attrs.size() > 0) {
                                if (fileName.endsWith(".xml")) {
                                    filenames.addFirst(fileName);
                                    com.commander4j.util.JWait.milliSec(50);
                                }
                            } else {
                                try {
                                    chld[i].delete();
                                } catch (Exception ex) {

                                }
                            }
                        } catch (IOException e) {

                        }

                    }

                    if (filenames.size() > 0) {
                        logger.debug("Begin processing " + String.valueOf(filenames.size()) + " files.");
                        for (int i = filenames.size() - 1; i >= 0; i--) {
                            if (allDone) {
                                if (dbconnected) {
                                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                                }
                                return;
                            }

                            fromFile = filenames.get(i);

                            try {
                                logger.debug("<---  START OF PROCESSING " + fromFile + "  ---->");
                                logger.debug("Reading message header : " + inputPath + fromFile);

                                if (gmh.readAddressInfo(inputPath + fromFile, getSessionID()) == true) {

                                    messageProcessedOK = true;
                                    errorMessage = "";

                                    if (gmh.getInterfaceType().length() == 0) {
                                        messageProcessedOK = false;
                                        errorMessage = "Unrecognised Commander4j XML message format in file "
                                                + fromFile;
                                        logger.debug(errorMessage);
                                        String datetime = "";
                                        datetime = JUtility
                                                .getISOTimeStampStringFormat(JUtility.getSQLDateTime());
                                        gmh.setMessageDate(datetime);
                                        gmh.setInterfaceDirection("Unknown");
                                        gmh.setMessageInformation(fromFile);
                                        gmh.setInterfaceType("Unknown");
                                        gmh.setMessageRef("Unknown");
                                    } else {
                                        if (gmh.getInterfaceDirection().equals("Input") == false) {
                                            messageProcessedOK = false;
                                            errorMessage = "Inbound message ignored - Interface Direction = "
                                                    + gmh.getInterfaceDirection();
                                        } else {
                                            String interfaceType = gmh.getInterfaceType();
                                            logger.debug("Processing " + interfaceType + " started.");
                                            if (interfaceType.equals("Despatch Confirmation") == true) {
                                                messageProcessedOK = idc.processMessage(gmh);
                                                errorMessage = idc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Material Definition") == true) {
                                                messageProcessedOK = imd.processMessage(gmh);
                                                errorMessage = imd.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Process Order") == true) {
                                                messageProcessedOK = ipo.processMessage(gmh);
                                                errorMessage = ipo.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Location") == true) {
                                                messageProcessedOK = ilocn.processMessage(gmh);
                                                errorMessage = ilocn.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Pallet Status Change") == true) {
                                                messageProcessedOK = ipsc.processMessage(gmh);
                                                errorMessage = ipsc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Pallet Move") == true) {
                                                messageProcessedOK = ipmv.processMessage(gmh);
                                                errorMessage = ipmv.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Batch Status Change") == true) {
                                                messageProcessedOK = bsc.processMessage(gmh);
                                                errorMessage = bsc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Journey Definition") == true) {
                                                messageProcessedOK = ij.processMessage(gmh);
                                                errorMessage = ij.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Process Order Status Change") == true) {
                                                messageProcessedOK = iposc.processMessage(gmh);
                                                errorMessage = iposc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Production Declaration") == true) {
                                                messageProcessedOK = ipd.processMessage(gmh);
                                                errorMessage = ipd.getErrorMessage();
                                            }

                                            if (interfaceType.equals("QM Inspection Request") == true) {
                                                messageProcessedOK = iireq.processMessage(gmh);
                                                errorMessage = iireq.getErrorMessage();
                                            }

                                            if (interfaceType.equals("QM Inspection Result") == true) {
                                                messageProcessedOK = iirslt.processMessage(gmh);
                                                errorMessage = iirslt.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Material Auto Move") == true) {
                                                messageProcessedOK = imam.processMessage(gmh);
                                                errorMessage = imam.getErrorMessage();
                                            }

                                            GenericMessageHeader.updateStats("Input", interfaceType,
                                                    messageProcessedOK.toString());

                                            logger.debug("Processing " + interfaceType + " finished.");
                                        }
                                    }

                                    logger.debug(
                                            "      ===  RESULT " + messageProcessedOK.toString() + "  ===");

                                    if (messageProcessedOK) {

                                        il.write(gmh, GenericMessageHeader.msgStatusSuccess, "Processed OK",
                                                "DB Update", fromFile);
                                        reader.deleteFile(backupPath + gmh.getInterfaceType() + File.separator
                                                + fromFile);
                                        reader.move_FileToDirectory(inputPath + fromFile,
                                                backupPath + gmh.getInterfaceType(), true);
                                    } else {
                                        il.write(gmh, GenericMessageHeader.msgStatusError, errorMessage,
                                                "DB Update", fromFile);
                                        if (inter.getInterfaceProperties(gmh.getInterfaceType(),
                                                "Input") == true) {
                                            if (inter.getEmailError() == true) {
                                                String emailaddresses = inter.getEmailAddresses();

                                                StringConverter stringConverter = new StringConverter();
                                                ArrayConverter arrayConverter = new ArrayConverter(
                                                        String[].class, stringConverter);
                                                arrayConverter.setDelimiter(';');
                                                arrayConverter.setAllowedChars(new char[] { '@', '_' });

                                                String[] emailList = (String[]) arrayConverter
                                                        .convert(String[].class, emailaddresses);

                                                if (emailList.length > 0) {
                                                    String siteName = Common.hostList.getHost(getHostID())
                                                            .getSiteDescription();
                                                    String attachedFilename = Common.base_dir
                                                            + java.io.File.separator + inputPath + fromFile;
                                                    logger.debug("Attaching file  " + Common.base_dir
                                                            + java.io.File.separator + inputPath + fromFile);
                                                    mail.postMail(emailList, "Error Processing Incoming "
                                                            + gmh.getInterfaceType() + " for [" + siteName
                                                            + "] on " + JUtility.getClientName(), errorMessage,
                                                            fromFile, attachedFilename);
                                                    com.commander4j.util.JWait.milliSec(2000);
                                                }
                                            }

                                        }
                                        reader.deleteFile(
                                                errorPath + gmh.getInterfaceType() + File.separator + fromFile);
                                        reader.move_FileToDirectory(inputPath + fromFile,
                                                errorPath + gmh.getInterfaceType(), true);
                                    }
                                }
                                logger.debug("<---  END OF PROCESSING " + fromFile + "  ---->");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}