Example usage for java.util LinkedList get

List of usage examples for java.util LinkedList get

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:org.alfresco.solr.query.Solr4QueryParser.java

/**
  * @param field//w w  w  . j  a v  a2 s.com
  * @return Query
  */
protected SpanOrQuery generateSpanOrQuery(String field,
        LinkedList<LinkedList<org.apache.lucene.analysis.Token>> fixedTokenSequences) {
    org.apache.lucene.analysis.Token nextToken;
    SpanOrQuery spanOr = new SpanOrQuery();

    for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : fixedTokenSequences) {
        int gap = 1;
        SpanQuery spanQuery = null;
        SpanOrQuery atSamePosition = new SpanOrQuery();

        // MNT-13239: if all tokens's positions are incremented by one then create flat nearQuery 
        if (getEnablePositionIncrements() && isAllTokensSequentiallyShifted(tokenSequence)) {
            // there will be no tokens at same position
            List<SpanQuery> wildWrappedList = new ArrayList<SpanQuery>(tokenSequence.size());
            for (org.apache.lucene.analysis.Token token : tokenSequence) {
                String termText = token.toString();
                Term term = new Term(field, termText);
                SpanQuery nextSpanQuery = wrapWildcardTerms(term);
                wildWrappedList.add(nextSpanQuery);
            }
            spanQuery = new SpanNearQuery(wildWrappedList.toArray(new SpanQuery[wildWrappedList.size()]), 0,
                    true);
        } else {
            for (int i = 0; i < tokenSequence.size(); i++) {
                nextToken = (org.apache.lucene.analysis.Token) tokenSequence.get(i);
                String termText = nextToken.toString();

                Term term = new Term(field, termText);

                if (getEnablePositionIncrements()) {
                    SpanQuery nextSpanQuery = wrapWildcardTerms(term);
                    if (gap == 0) {
                        atSamePosition.addClause(nextSpanQuery);
                    } else {
                        if (atSamePosition.getClauses().length == 0) {
                            if (spanQuery == null) {
                                spanQuery = nextSpanQuery;
                            } else {
                                spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, nextSpanQuery },
                                        (gap - 1) + internalSlop, internalSlop < 2);
                            }
                            atSamePosition = new SpanOrQuery();
                        } else if (atSamePosition.getClauses().length == 1) {
                            if (spanQuery == null) {
                                spanQuery = atSamePosition.getClauses()[0];
                            } else {
                                spanQuery = new SpanNearQuery(
                                        new SpanQuery[] { spanQuery, atSamePosition.getClauses()[0] },
                                        (gap - 1) + internalSlop, internalSlop < 2);
                            }
                            atSamePosition = new SpanOrQuery();
                            atSamePosition.addClause(nextSpanQuery);
                        } else {
                            if (spanQuery == null) {
                                spanQuery = atSamePosition;
                            } else {
                                spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, atSamePosition },
                                        (gap - 1) + internalSlop, internalSlop < 2);
                            }
                            atSamePosition = new SpanOrQuery();
                            atSamePosition.addClause(nextSpanQuery);
                        }
                    }
                    gap = nextToken.getPositionIncrement();

                } else {
                    SpanQuery nextSpanQuery;
                    if ((termText != null) && (termText.contains("*") || termText.contains("?"))) {
                        org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery(
                                term);
                        SpanMultiTermQueryWrapper wrapper = new SpanMultiTermQueryWrapper<>(wildQuery);
                        wrapper.setRewriteMethod(new TopTermsSpanBooleanQueryRewrite(topTermSpanRewriteLimit));
                        nextSpanQuery = wrapper;
                    } else {
                        nextSpanQuery = new SpanTermQuery(term);
                    }
                    if (spanQuery == null) {
                        spanQuery = new SpanOrQuery();
                        ((SpanOrQuery) spanQuery).addClause(nextSpanQuery);
                    } else {
                        ((SpanOrQuery) spanQuery).addClause(nextSpanQuery);
                    }
                }
            }
        }

        if (atSamePosition.getClauses().length == 0) {
            spanOr.addClause(spanQuery);
        } else if (atSamePosition.getClauses().length == 1) {
            if (spanQuery == null) {
                spanQuery = atSamePosition.getClauses()[0];
            } else {
                spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, atSamePosition.getClauses()[0] },
                        (gap - 1) + internalSlop, internalSlop < 2);
            }
            atSamePosition = new SpanOrQuery();
            spanOr.addClause(spanQuery);
        } else {
            if (spanQuery == null) {
                spanQuery = atSamePosition;
            } else {
                spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, atSamePosition },
                        (gap - 1) + internalSlop, internalSlop < 2);
            }
            atSamePosition = new SpanOrQuery();
            spanOr.addClause(spanQuery);
        }
    }
    return spanOr;
}

From source file:org.jahia.utils.maven.plugin.contentgenerator.bo.PageBO.java

private void buildPageElement() {

    pageElement = new Element(getName());
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JCR);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_NT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JNT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_TEST);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JMIX);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_J);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_REP);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_WEM);

    pageElement.setAttribute("changefreq", "monthly");
    pageElement.setAttribute("templateName", pageTemplate, ContentGeneratorCst.NS_J);
    pageElement.setAttribute("primaryType", "jnt:page", ContentGeneratorCst.NS_JCR);
    pageElement.setAttribute("priority", "0.5");

    String mixinTypes = "jmix:sitemap";
    if (hasVanity) {
        mixinTypes = mixinTypes + " jmix:vanityUrlMapped";
    }/* w  w w  .j  a v a 2 s  .c  om*/
    pageElement.setAttribute("mixinTypes", mixinTypes, ContentGeneratorCst.NS_JCR);

    if (idCategory != null) {
        pageElement.setAttribute("jcategorized", StringUtils.EMPTY, ContentGeneratorCst.NS_JMIX);
        pageElement.setAttribute("defaultCategory", "/sites/systemsite/categories/category" + idCategory,
                ContentGeneratorCst.NS_J);
    }

    if (idTag != null) {
        pageElement.setAttribute("tags", "/sites/" + siteKey + "/tags/tag" + idTag, ContentGeneratorCst.NS_J);
    }

    // articles
    for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
        Element translationNode = new Element("translation_" + entry.getKey(), ContentGeneratorCst.NS_J);
        translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("mixinTypes", "mix:title", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("title", entry.getValue().getTitle(), ContentGeneratorCst.NS_JCR);

        if (StringUtils.isNotEmpty(description)) {
            translationNode.setAttribute("description", description, ContentGeneratorCst.NS_JCR);
        }
        pageElement.addContent(translationNode);
    }

    if (!acls.isEmpty()) {
        Element aclNode = new Element("acl", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("inherit", "true", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("primaryType", "jnt:acl", ContentGeneratorCst.NS_JCR);

        for (Map.Entry<String, List<String>> entry : acls.entrySet()) {
            String roles = "";
            for (String s : entry.getValue()) {
                roles += s + " ";
            }
            Element aceNode = new Element("GRANT_" + entry.getKey().replace(":", "_"));
            aceNode.setAttribute("aceType", "GRANT", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("principal", entry.getKey(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("protected", "false", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("roles", roles.trim(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("primaryType", "jnt:ace", ContentGeneratorCst.NS_JCR);

            aclNode.addContent(aceNode);
        }
        pageElement.addContent(aclNode);
    }

    // begin content list
    Element listNode = new Element("listA");
    listNode.setAttribute("primaryType", "jnt:contentList", ContentGeneratorCst.NS_JCR);

    LinkedList<Element> personalizableElements = new LinkedList<Element>();

    if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_QALIST)) {

        List<String> languages = new ArrayList<String>();
        for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
            languages.add(entry.getKey());
        }
        for (int i = 1; i <= ContentGeneratorCst.NB_NEWS_IN_QALIST; i++) {
            Element newsNode = new NewsBO(namePrefix + "-" + "news" + i, languages).getElement();
            listNode.addContent(newsNode);
            if (i <= ContentGeneratorCst.NB_NEWS_PER_PAGE_IN_QALIST) {
                // News are split to multiple pages by Jahia at runtime, so only personalize items present on the first page.
                personalizableElements.add(newsNode);
            }
        }
    } else if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_DEFAULT)) {
        for (int i = 1; i <= numberBigText.intValue(); i++) {
            Element bigTextNode = new Element("bigText_" + i);
            bigTextNode.setAttribute("primaryType", "jnt:bigText", ContentGeneratorCst.NS_JCR);
            bigTextNode.setAttribute("mixinTypes", "jmix:renderable", ContentGeneratorCst.NS_JCR);
            for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
                Element translationNode = new Element("translation_" + entry.getKey(),
                        ContentGeneratorCst.NS_J);
                translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("text", entry.getValue().getContent());
                bigTextNode.addContent(translationNode);
            }
            listNode.addContent(bigTextNode);
            personalizableElements.add(bigTextNode);
        }
    }

    // for pages with external/internal file reference, we check the page name
    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAEXTERNAL)) {
        for (int i = 0; i < externalFilePaths.size(); i++) {
            String externalFilePath = externalFilePaths.get(i);
            Element externalFileReference = new Element("external-file-reference-" + i);
            externalFileReference.setAttribute("node", "/mounts/" + ContentGeneratorCst.CMIS_MOUNT_POINT_NAME
                    + "/Sites/" + cmisSite + externalFilePath, ContentGeneratorCst.NS_J);
            externalFileReference.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);
            listNode.addContent(externalFileReference);
            personalizableElements.add(externalFileReference);
        }
    }

    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAINTERNAL) && fileName != null) {

        Element randomFileNode = new Element("rand-file");
        randomFileNode.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);

        Element fileTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        fileTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("title", "My file", ContentGeneratorCst.NS_JCR);

        randomFileNode.addContent(fileTranslationNode);

        Element publicationNode = new Element("publication");
        publicationNode.setAttribute("primaryType", "jnt:publication", ContentGeneratorCst.NS_JCR);

        Element publicationTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        publicationTranslationNode.setAttribute("author", "Jahia Content Generator");
        publicationTranslationNode.setAttribute("body", "&lt;p&gt;  Random publication&lt;/p&gt;");
        publicationTranslationNode.setAttribute("title", "Random publication", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("file", "/sites/" + siteKey + "/files/contributed/"
                + org.apache.jackrabbit.util.ISO9075.encode(fileName));
        publicationTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("source", "Jahia");

        publicationNode.addContent(publicationTranslationNode);

        listNode.addContent(publicationNode);
    }

    if (personalized) {
        if (personalizableElements.isEmpty()) {
            personalized = false;
            pageElement.setName(getName()); // Re-set the root element name: it must change according to page personalization change.
        } else {
            Element element = personalizableElements
                    .get(ThreadLocalRandom.current().nextInt(personalizableElements.size()));
            int elementIndex = listNode.indexOf(element);
            listNode.removeContent(element);
            element = getPersonalizedElement(element);
            listNode.addContent(elementIndex, element);
        }
    }

    // end content list
    pageElement.addContent(listNode);

    if (hasVanity) {

        Element vanityNode = new Element("vanityUrlMapping");
        vanityNode.setAttribute("primaryType", "jnt:vanityUrls", ContentGeneratorCst.NS_JCR);

        Element vanitySubNode = new Element(namePrefix);
        vanitySubNode.setAttribute("active", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("default", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("url", "/" + namePrefix, ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        vanitySubNode.setAttribute("primaryType", "jnt:vanityUrl", ContentGeneratorCst.NS_JCR);

        vanityNode.addContent(vanitySubNode);
        pageElement.addContent(vanityNode);
    }

    if (visibilityEnabled) {

        Element visibilityNode = new Element("conditionalVisibility", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("conditionalVisibility", null, ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("forceMatchAllConditions", "true", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("primaryType", "jnt:conditionalVisibility", ContentGeneratorCst.NS_JCR);

        Element visibilityConditionNode = new Element("startEndDateCondition0", ContentGeneratorCst.NS_JNT);
        visibilityConditionNode.setAttribute("primaryType", "jnt:startEndDateCondition",
                ContentGeneratorCst.NS_JCR);
        visibilityConditionNode.setAttribute("start", visibilityStartDate);
        visibilityConditionNode.setAttribute("end", visibilityEndDate);

        visibilityNode.addContent(visibilityConditionNode);
        pageElement.addContent(visibilityNode);
    }

    if (null != subPages) {
        for (Iterator<PageBO> iterator = subPages.iterator(); iterator.hasNext();) {
            PageBO subPage = iterator.next();
            pageElement.addContent(subPage.getElement());
        }
    }
}

From source file:com.ephesoft.gxt.admin.server.BatchClassManagementServiceImpl.java

public List<Span> getSpanValues(final BatchClassDTO batchClassDTO, String imageName, String docName,
        LinkedList<Integer> pageProp) throws Exception {
    LOGGER.debug(EphesoftStringUtil.concatenate("Getting Span Values for image : ", imageName));
    List<Span> values = null;
    String uploadedImageName = imageName;

    if (imageName.contains(FileType.PDF.getExtensionWithDot())) {
        uploadedImageName = FileUtils.changeFileExtension(imageName, FileType.TIF.getExtension());
    }/*from   w ww . j  a  va2  s.c om*/
    try {
        if (batchClassDTO == null) {
            LOGGER.debug("Batch Class DTO is null.");
            throw new Exception(BatchClassMessages.TEST_KV_FAILURE);
        }
        if (docName == null) {
            LOGGER.debug("Document Name is null.");
            throw new Exception(BatchClassMessages.TEST_KV_FAILURE);
        }
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        // Get path upto test-advanced-extraction folder.
        String testKVFolderPath = batchSchemaService
                .getTestAdvancedKvExtractionFolderPath(batchClassDTO.getIdentifier(), true);
        if (testKVFolderPath == null) {
            LOGGER.info("Test KV Folder path is null");
            throw new Exception(BatchClassMessages.TEST_KV_FAILURE);
        }
        testKVFolderPath = EphesoftStringUtil.concatenate(testKVFolderPath, File.separator, docName);
        String testKVFileName = EphesoftStringUtil.concatenate(testKVFolderPath, File.separator,
                uploadedImageName);
        File destinationImageFile = new File(testKVFileName);
        // Creating an Empty Image of same size.
        String emptyImageName = EphesoftStringUtil.concatenate(
                testKVFileName.substring(0, testKVFileName.lastIndexOf(FileType.TIF.getExtensionWithDot())),
                "empty", FileType.PNG.getExtensionWithDot());

        BufferedImage image = new BufferedImage(pageProp.get(0), pageProp.get(1), BufferedImage.TYPE_INT_RGB);
        image.getGraphics().setColor(Color.WHITE);
        image.getGraphics().fillRect(0, 0, image.getWidth(), image.getHeight());
        File file = new File(emptyImageName);
        ImageIO.write(image, "PNG", file);
        if (destinationImageFile.exists()) {
            SearchClassificationService searchClassificationService = this
                    .getSingleBeanOfType(SearchClassificationService.class);
            String ocrEngineName = getOCRPluginNameForBatchClass(batchClassDTO.getIdentifier());
            Map<String, String> imageToOCRFilePath = searchClassificationService
                    .generateHOCRForKVExtractionTest(testKVFolderPath, ocrEngineName,
                            batchClassDTO.getIdentifier(), new File(destinationImageFile.getAbsolutePath()),
                            true);
            for (String imagePath : imageToOCRFilePath.keySet()) {
                String hocrFilePath = imageToOCRFilePath.get(imagePath);
                HocrPages hocrPages = batchSchemaService.getHOCR(hocrFilePath);
                if (hocrPages != null) {
                    HocrPage hocrPage = hocrPages.getHocrPage().get(0);
                    final Spans spans = hocrPage.getSpans();
                    values = spans.getSpan();
                    LOGGER.debug("Span Size" + values.size());
                }
            }
        } else {
            LOGGER.error(EphesoftStringUtil.concatenate("Image doesn't exist = ",
                    destinationImageFile.getAbsolutePath(), ". Cannot continue ocring..."));
            throw new Exception(EphesoftStringUtil.concatenate("Image Not Found : ",
                    destinationImageFile.getAbsolutePath()));
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new Exception(BatchClassMessages.TEST_KV_FAILURE);
    }

    return values;
}

From source file:controllers.controller.java

private void insertarObjetoArchivo(HttpSession session, HttpServletRequest request,
        HttpServletResponse response, QUID quid, PrintWriter out, HashMap parameters, LinkedList filesToUpload,
        String FormFrom) throws Exception {
    if (parameters.get("idTipoArchivo") == null || parameters.get("idTipoArchivo").equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de archivo.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("nombreArchivo") == null || parameters.get("nombreArchivo").equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba el nombre del archivo.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("descripcion") == null
            || parameters.get("descripcion").toString().trim().equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba una descripcin.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("tipoAcceso").equals("")) {
        this.getServletConfig().getServletContext().getRequestDispatcher(""
                + PageParameters.getParameter("msgUtil")
                + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de acceso para el archivo.&url="
                + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (filesToUpload.isEmpty()) {
        this.getServletConfig().getServletContext().getRequestDispatcher(""
                + PageParameters.getParameter("msgUtil")
                + "/msgNRedirect.jsp?title=Error&type=error&msg=No ha seleccionado ningn archivo.&url="
                + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (!filesToUpload.isEmpty()) {
        String idObjeto = WebUtil.decode(session, parameters.get("idObjeto").toString());
        String fechaActualizacion = UTime.calendar2SQLDateFormat(Calendar.getInstance());
        String descripcion = WebUtil.decode(session, parameters.get("descripcion").toString());
        String ubicacionFisica = PageParameters.getParameter("folderDocs");
        String idTipoArchivo = WebUtil.decode(session, parameters.get("idTipoArchivo").toString());
        String nombreObjeto = WebUtil.decode(session, parameters.get("nombreObjeto").toString());
        String keyWords = parameters.get("keywords").toString();
        String nombreArchivo = parameters.get("nombreArchivo").toString();
        String FK_ID_Plantel = session.getAttribute("FK_ID_Plantel").toString();

        //File verifyFolder = new File(PageParameters.getParameter("folderDocs"));
        File verifyFolder = new File(ubicacionFisica);
        if (!verifyFolder.exists()) {
            verifyFolder.mkdirs();/*w w w  .ja  va2 s .  co m*/
        }
        int sucess = 0;
        for (int i = 0; i < filesToUpload.size(); i++) {
            FileItem itemToUpload = null;
            itemToUpload = (FileItem) filesToUpload.get(i);

            String extension = FileUtil.getExtension(itemToUpload.getName());
            String hashName = JHash.getFileDigest(itemToUpload.get(), "MD5") + extension;

            long tamanio = itemToUpload.getSize();

            if (this.validarDocumentExtension(session, request, response, quid, out, extension)) {
                File fileToWrite = new File(ubicacionFisica, hashName);
                Transporter tport = quid.insertArchivo4Objeto(idObjeto, nombreObjeto, idTipoArchivo,
                        nombreArchivo, descripcion, ubicacionFisica, extension, fechaActualizacion, tamanio,
                        WebUtil.decode(session, parameters.get("tipoAcceso").toString()).toLowerCase(),
                        keyWords, hashName, FK_ID_Plantel);
                if (tport.getCode() == 0) {
                    if (!fileToWrite.exists()) {
                        itemToUpload.write(fileToWrite);
                    }
                    sucess += 1;
                }
            } else {
                sucess = -1;
            }
        }
        if (sucess != -1) {
            this.getServletConfig().getServletContext()
                    .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                            + "/msgNRedirect.jsp?title=Operacin Exitosa&type=info&msg=Se han guardado "
                            + sucess + " de " + filesToUpload.size() + " archivos.&url="
                            + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                            + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                            + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                            + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                    .forward(request, response);
        }

    }

}

From source file:com.peterbochs.PeterBochsDebugger.java

private void jLoadBreakpointButtonActionPerformed(ActionEvent evt) {
    if (jLoadBreakpointButton.getEventSource() == loadElfMenuItem) {
        JFileChooser fc = new JFileChooser(new File("."));
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            sourceLevelDebugger.loadELF(file, null, 0);
        }/* w  w  w  .j  a  v a  2s  .  co  m*/
    } else {
        jLoadBreakpointButton.setEnabled(false);
        LinkedList<Breakpoint> vector = Setting.getInstance().getBreakpoint();
        try {
            for (int x = 0; x < vector.size(); x++) {
                boolean match = false;
                for (int y = 0; y < this.breakpointTable.getRowCount(); y++) {
                    if (vector.get(x).getAddress().trim()
                            .equals(breakpointTable.getValueAt(y, 2).toString().trim())) {
                        match = true;
                        break;
                    }
                }
                if (!match) {
                    if (vector.get(x).getType().contains("pbreakpoint")) {
                        sendCommand("pb " + vector.get(x).getAddress());
                    } else {
                        sendCommand("lb " + vector.get(x).getAddress());
                    }
                    if (vector.get(x).getEnable().trim().equals("keep n")) {
                        sendCommand("bpd " + (x + 1));
                    }
                }
            }
        } catch (Exception e) {
            if (Global.debug) {
                e.printStackTrace();
            }
        }
        updateBreakpoint();
        updateBreakpointTableColor();
        jLoadBreakpointButton.setEnabled(true);
    }
}

From source file:com.nest5.businessClient.Initialactivity.java

@Override
public void OnOrderClicked(int isDelivery, int isTogo, String note) {
    // al guardar lo que hace es que guarda un objeto Sale con fecha, metodo
    // de pago y valor recibido.
    // despues toma currentOrder y dic saveItem(Context mContext,int type,
    // long item_id, double qty) para cada uno

    // al recuperar un sale se hace

    // price = 0.0;
    Date date = new Date();
    String fecha = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(date);
    //String fecha = DateFormat.getDateFormat(Initialactivity.this).format(
    //date);/*from ww w.j  a  v  a2 s  . c  o  m*/

    // imprimir, conectar por wifi y enviar el texto arregladito a la app de
    // puente
    String mesa = "-DOMICILIO / PARA LLEVAR- O -MESA NO REGISTRADA-";
    if (currentTable != null) {
        mesa = currentTable.getTable().getName().toUpperCase(Locale.getDefault());
    }
    int lines = 0;
    StringBuilder factura = new StringBuilder();
    String newline = "\r\n";
    String title = "-----COMANDA----COMANDA-----" + "\r\n";
    String tableheader = "    Item              Cantidad\r\n";
    String notas = "NOTAS\r\n";
    factura.append(title);
    factura.append(mesa + "\r\n");
    lines++;
    factura.append(fecha);
    lines++;
    lines++;
    lines++;
    factura.append(newline);
    factura.append(tableheader);

    lines++;
    int j = 0;
    LinkedList<String> productos = new LinkedList<String>();
    LinkedList<Integer> quantities = new LinkedList<Integer>();
    LinkedList<Double> precios = new LinkedList<Double>();

    Iterator<Entry<Registrable, Integer>> it = currentOrder.entrySet().iterator();
    // Log.d(TAG,String.valueOf(currentOrder.size()));
    LinkedHashMap<Registrable, Integer> currentObjects = new LinkedHashMap<Registrable, Integer>();

    while (it.hasNext()) {

        LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) it.next();

        currentObjects.put(pairs.getKey(), pairs.getValue());
        String name = pairs.getKey().name;
        productos.add(name);
        int longName = name.length();
        int subLength = 14 - longName;
        if (subLength < 0)
            name = name.substring(0, 14);
        int espacios1 = 4;
        int espacios2 = 12;
        if (name.length() < 14) {
            espacios1 += 14 - name.length();
        }
        factura.append(name);

        int qtyL = String.valueOf(pairs.getValue()).length();
        espacios1 = espacios1 - qtyL < 1 ? espacios1 = 1 : espacios1 - qtyL;
        //espacios2 = espacios2 - priceL < 1 ? espacios2 = 1 : espacios2 - priceL;
        espacios2 = espacios2 - qtyL < 1 ? espacios2 = 1 : espacios2 - qtyL;
        for (int k = 0; k < espacios1; k++) {
            factura.append(" ");
        }
        factura.append(pairs.getValue());
        quantities.add(pairs.getValue());
        for (int k = 0; k < espacios2; k++) {
            factura.append(" ");
        }
        factura.append(newline);
        lines++;
    }
    factura.append(notas);
    factura.append(note);
    long startTime = System.currentTimeMillis();
    if (currentSelectedAddTable > -1) {//esto significa que esta agregando la orden actual a otra existente, para la mesa que este seleccionada
        LinkedHashMap<Registrable, Integer> existingOrder = null;
        for (Map.Entry<LinkedHashMap<Registrable, Integer>, CurrentTable<Table, Integer>> tab : cookingOrdersTable
                .entrySet()) {
            if (tab.getValue().getTable().getName().equalsIgnoreCase(currentTable.getTable().getName())) {
                existingOrder = tab.getKey();
                break;
            }
        }
        if (existingOrder != null) {
            int prevDelivery = cookingOrdersDelivery.get(existingOrder);
            int prevTogo = cookingOrdersTogo.get(existingOrder);
            Long prevTime = cookingOrdersTimes.get(existingOrder);
            cookingOrders.remove(existingOrder);
            cookingOrdersDelivery.remove(existingOrder);
            cookingOrdersTable.remove(existingOrder);
            cookingOrdersTimes.remove(existingOrder);
            cookingOrdersTogo.remove(existingOrder);
            Iterator<Entry<Registrable, Integer>> itnuevo = existingOrder.entrySet().iterator();

            while (itnuevo.hasNext()) {
                LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) itnuevo
                        .next();
                currentObjects.put(pairs.getKey(), pairs.getValue());
            }
            cookingOrders.add(currentObjects);
            cookingOrdersDelivery.put(currentObjects, prevDelivery);
            cookingOrdersTogo.put(currentObjects, prevTogo);
            cookingOrdersTimes.put(currentObjects, prevTime);
            cookingOrdersTable.put(currentObjects, currentTable);
        }
    } else {
        cookingOrders.add(currentObjects);
        cookingOrdersDelivery.put(currentObjects, isDelivery);
        cookingOrdersTogo.put(currentObjects, isTogo);
        cookingOrdersTimes.put(currentObjects, startTime);
        if (currentTable != null) {
            cookingOrdersTable.put(currentObjects, currentTable);
            openTables.push(currentTable);
        } else {
            int[] coordinates = new int[2];
            coordinates[0] = 0;
            coordinates[1] = 0;
            CurrentTable<Table, Integer> tabletemp = new CurrentTable<Table, Integer>(
                    new Table("Domicilio / Para Llevar", 1, coordinates), 1);
            cookingOrdersTable.put(currentObjects, tabletemp);
            openTables.push(tabletemp);
        }
    }

    List<Long> items = new ArrayList<Long>();
    List<String> nameTables = new ArrayList<String>();
    for (LinkedHashMap<Registrable, Integer> current : cookingOrders) {
        items.add(cookingOrdersTimes.get(current));
        nameTables.add(cookingOrdersTable.get(current).getTable().getName());
    }
    cookingAdapter = new SaleAdapter(mContext, items, nameTables, inflater);
    ordersList.setAdapter(cookingAdapter);
    ordersList.setOnItemClickListener(orderListListener);
    /*if (!isTimerRunning) {
       startTimer();
    }*/
    currentOrder.clear();
    currentTable = null;
    statusText.setText("En Espera de Abrir mesa.");
    makeTable("NA");
    lines++;
    lines++;
    Boolean printed = true;
    try {
        if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
            try {
                mChatService.write(factura.toString().getBytes("x-UnicodeBig"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            printed = false;
            Toast.makeText(mContext, "No hay impresora conectada.", Toast.LENGTH_LONG).show();
        }
    } catch (NullPointerException e) {
        printed = false;
        e.printStackTrace();
    }
    if (!printed) {//buscar impresora TCP/IP
        StringBuilder formateado = new StringBuilder();
        formateado.append(CLEAR_PRINTER);
        formateado.append(INITIALIZE_PRINTER);
        formateado.append(JUSTIFICATION_CENTER);
        formateado.append(DOUBLE_WIDE_CHARACTERS);
        formateado.append("----COMANDA----");
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(fecha);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(mesa);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x03);
        formateado.append(JUSTIFICATION_LEFT);
        formateado.append("ITEM");
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append("CANTIDAD");
        formateado.append(HORIZONTAL_TAB);
        formateado.append(SINGLE_WIDE_CHARACTERS);
        formateado.append(PRINT_FEED_ONE_LINE);
        for (String actual : productos) {
            int pos = productos.indexOf(actual);
            int cantidad = quantities.get(pos);
            formateado.append(actual);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(cantidad);
            formateado.append(PRINT_FEED_ONE_LINE);
        }
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append(ITALIC_STYLE);
        formateado.append(notas);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(note);
        formateado.append(ITALIC_CANCEL);
        formateado.append(FINALIZE_TICKET);
        formateado.append(PARTIAL_CUT);
        if (mTCPPrint != null) {
            if (mTCPPrint.getStatus() == TCPPrint.CONNECTED) {
                mTCPPrint.sendMessage(formateado.toString());
                mTCPPrint.sendMessage(formateado.toString());
            } else {
                mTCPPrint.stopClient();
                new connectTask().execute(formateado.toString());
                alertbox("Oops!",
                        "Al Parecer no hay impresora disponible. Estamos tratando de reconectarnos e imprimir. Si no funciona, reinicia la Red o la impresora y ve a rdenes para imprimir el pedido.");
            }
        } else {
            alertbox("Oops!",
                    "Al Parecer no hay impresora disponible. Trataremos en este momento de nuevo de imprimir el pedido. Si no funciona, reinicia la red o la impreso y ve a rdenes para imprimir de nuevo la orden.");
            new connectTask().execute(formateado.toString());
        }
    }

}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * @param toSync//from w w w  .ja va  2  s . c  o  m
 * @param account
 * @param extras
 * @param provider
 * @param syncResult
 * @return true if the item was sync'd successfully. Soft errors will cause this to return
 *         false.
 * @throws RemoteException
 * @throws SyncException
 * @throws JSONException
 * @throws IOException
 * @throws NetworkProtocolException
 * @throws NoPublicPath
 * @throws OperationApplicationException
 * @throws InterruptedException
 */
public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException,
        NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException {

    String pubPath = null;

    //
    // Handle http or https uris separately. These require the
    // destination uri.
    //
    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        pubPath = toSync.toString();

        if (!extras.containsKey(EXTRA_DESTINATION_URI)) {
            throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs");
        }
        toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI));
    }

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);

    // skip any items already sync'd
    if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) {
        if (DEBUG) {
            Log.d(TAG, "not syncing " + toSync + " as it's been updated recently");
        }
        syncResult.stats.numSkippedEntries++;
        return false;
    }

    // the sync map will convert the json data to ContentValues
    final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync);

    final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build();

    final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>();
    final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>();
    final LinkedList<String> cpoPubUris = new LinkedList<String>();

    //
    // first things first, upload any content that needs to be
    // uploaded.
    //

    try {
        uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult);

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // this should ensure that all items have a pubPath when we
        // query it below.

        if (pubPath == null) {
            // we should avoid calling this too much as it
            // can be expensive
            pubPath = MediaProvider.getPublicPath(mContext, toSync);
        }
    } catch (final NoPublicPath e) {
        // TODO this is a special case and this is probably not the best place to handle this.
        // Ideally, this should be done in such a way as to reduce any extra DB queries -
        // perhaps by doing a join with the parent.
        if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) {
            if (DEBUG) {
                Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first");
            }
            syncResult.stats.numSkippedEntries++;
            return false;
        }

        // if it's an item, we can handle it.
        if (isDir) {
            throw e;
        }
    }

    if (pubPath == null) {

        // this should have been updated already by the initial
        // upload, so something must be wrong
        throw new SyncException("never got a public path for " + toSync);
    }

    if (DEBUG) {
        Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync="
                + manualSync + ",...)");
        Log.d(TAG, "pubPath: " + pubPath);
    }

    final long request_time = System.currentTimeMillis();

    HttpResponse hr = mNetworkClient.get(pubPath);

    final long response_time = System.currentTimeMillis();

    // the time compensation below allows a time-based synchronization to function even if the
    // local clock is entirely wrong. The server's time is extracted using the Date header and
    // all are compared relative to the respective clock reference. Any data that's stored on
    // the mobile should be stored relative to the local clock and the server will respect the
    // same.
    long serverTime;

    try {
        serverTime = getServerTime(hr);
    } catch (final DateParseException e) {
        Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e);
        serverTime = System.currentTimeMillis();
    }

    // TODO check out
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
    final long response_delay = response_time - request_time;
    if (DEBUG) {
        Log.d(TAG, "request took " + response_delay + "ms");
    }
    final long localTime = request_time;

    // add this to the server time to get the local time
    final long localOffset = (localTime - serverTime);

    if (Math.abs(localOffset) > 30 * 60 * 1000) {
        Log.w(TAG, "local clock is off by " + localOffset + "ms");
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    final HttpEntity ent = hr.getEntity();

    String selection;
    String selectionInverse;
    String[] selectionArgs;

    if (isDir) {

        final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();

        final int len = ja.length();
        selectionArgs = new String[len];

        // build the query to see which items are already in the
        // database
        final StringBuilder sb = new StringBuilder();

        sb.append("(");

        for (int i = 0; i < len; i++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime);

            syncStatuses.put(syncStatus.remote, syncStatus);

            selectionArgs[i] = syncStatus.remote;

            // add in a placeholder for the query
            sb.append('?');
            if (i != (len - 1)) {
                sb.append(',');
            }

        }
        sb.append(")");

        final String placeholders = sb.toString();
        selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders;
        selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders;
    } else {

        final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();
        final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime);

        syncStatuses.put(syncStatus.remote, syncStatus);

        selection = JsonSyncableItem._PUBLIC_URI + "=?";
        selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?";
        selectionArgs = new String[] { syncStatus.remote };
    }

    // first check without the querystring. This will ensure that we
    // properly mark things that we already have in the database.
    final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs,
            null);

    // these items are on both sides
    try {
        final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int idCol = check.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = check.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = check.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            itemStatus.state = SyncState.BOTH_UNKNOWN;

            itemStatus.local = localUri;

            // make the status searchable by both remote and
            // local uri
            syncStatuses.put(localUri.toString(), itemStatus);
        }
    } finally {
        check.close();
    }

    Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null);

    // these items are on both sides
    try {
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE);
        final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE);
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = c.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = c.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE
                    || itemStatus.state == SyncState.NOW_UP_TO_DATE) {
                if (DEBUG) {
                    Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date.");
                }
                continue;
            }

            itemStatus.local = localUri;

            // make the status searchable by both remote and local uri
            syncStatuses.put(localUri.toString(), itemStatus);

            // last modified as stored in the DB, in phone time
            final long itemLocalModified = c.getLong(localModifiedCol);

            // last modified as stored in the DB, in server time
            final long itemServerModified = c.getLong(serverModifiedCol);
            final long localAge = localTime - itemLocalModified;

            final long remoteAge = serverTime - itemStatus.remoteModifiedTime;

            final long ageDifference = Math.abs(localAge - remoteAge);

            // up to date, as far remote -> local goes
            if (itemServerModified == itemStatus.remoteModifiedTime) {
                itemStatus.state = SyncState.ALREADY_UP_TO_DATE;
                if (DEBUG) {
                    Log.d(TAG, pubUri + " is up to date.");
                }

                // need to download
            } else if (localAge > remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms older ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); updating local copy...");
                }

                itemStatus.state = SyncState.REMOTE_DIRTY;

                final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri);

                // update this so it's in the local timescale
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE,
                        JsonSyncableItem._CREATED_DATE, localOffset);
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                        JsonSyncableItem._MODIFIED_DATE, localOffset);

                b.withValues(itemStatus.remoteCVs);
                b.withExpectedCount(1);

                cpo.add(b.build());
                cpoPubUris.add(pubUri);

                syncResult.stats.numUpdates++;

                // need to upload
            } else if (localAge < remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms newer ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); publishing to server...");
                }
                itemStatus.state = SyncState.LOCAL_DIRTY;

                mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap));
            }

            mLastUpdated.markUpdated(localUri);

            syncResult.stats.numEntries++;
        } // end for
    } finally {

        c.close();
    }

    /*
     * Apply updates in bulk
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "applying " + cpo.size() + " bulk updates...");
        }

        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "Done applying updates. Running postSync handler...");
        }

        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i));
            if (ss == null) {
                Log.e(TAG, "can't get sync status for " + res.uri);
                continue;
            }
            syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
        }

        if (DEBUG) {
            Log.d(TAG, "done running postSync handler.");
        }

        cpo.clear();
        cpoPubUris.clear();
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    /*
     * Look through the SyncState.state values and find ones that need to be stored.
     */

    for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        final String pubUri = entry.getKey();
        final SyncStatus status = entry.getValue();
        if (status.state == SyncState.REMOTE_ONLY) {
            if (DEBUG) {
                Log.d(TAG, pubUri + " is not yet stored locally, adding...");
            }

            // update this so it's in the local timescale
            correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE,
                    JsonSyncableItem._CREATED_DATE, localOffset);
            correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                    JsonSyncableItem._MODIFIED_DATE, localOffset);

            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync);
            b.withValues(status.remoteCVs);

            cpo.add(b.build());
            cpoPubUris.add(pubUri);
            syncResult.stats.numInserts++;

        }
    }

    /*
     * Execute the content provider operations in bulk.
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "bulk inserting " + cpo.size() + " items...");
        }
        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "applyBatch completed. Processing results...");
        }

        int successful = 0;
        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            if (res.uri == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "result from content provider bulk operation returned null");
                continue;
            }
            final String pubUri = cpoPubUris.get(i);
            final SyncStatus ss = syncStatuses.get(pubUri);

            if (ss == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i));
                continue;
            }

            ss.local = res.uri;
            if (DEBUG) {
                Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri);
            }

            syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
            successful++;
        }
        if (DEBUG) {
            Log.d(TAG, successful + " batch inserts successfully applied.");
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "no updates to perform.");
        }
    }

    /**
     * Look through all the items that we didn't already find on the server side, but which
     * still have a public uri. They should be checked to make sure they're not deleted.
     */
    c = provider.query(toSync, SYNC_PROJECTION,
            ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"),
            selectionArgs, null);

    try {
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);

        cpo.clear();

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            final String pubUri = c.getString(pubUriCol);
            SyncStatus ss = syncStatuses.get(pubUri);

            final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))
                    : toSync;

            if (ss == null) {
                ss = syncStatuses.get(item.toString());
            }

            if (DEBUG) {
                Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath
                        + "), but appears to be a child of " + toSync);

                if (ss != null) {
                    Log.d(TAG, "found sync status for " + item + ": " + ss);
                }
            }

            if (ss != null) {
                switch (ss.state) {
                case ALREADY_UP_TO_DATE:
                case NOW_UP_TO_DATE:
                    if (DEBUG) {
                        Log.d(TAG, item + " is already up to date. No need to see if it was deleted.");
                    }
                    continue;

                case BOTH_UNKNOWN:
                    if (DEBUG) {
                        Log.d(TAG,
                                item + " was found on both sides, but has an unknown sync status. Skipping...");
                    }
                    continue;

                default:

                    Log.w(TAG, "got an unexpected state for " + item + ": " + ss);
                }

            } else {
                ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY);
                ss.local = item;

                hr = mNetworkClient.head(pubUri);

                switch (hr.getStatusLine().getStatusCode()) {
                case 200:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 200");
                    }
                    ss.state = SyncState.BOTH_UNKNOWN;
                    break;

                case 404:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally...");
                    }
                    ss.state = SyncState.DELETED_REMOTELY;
                    final ContentProviderOperation deleteOp = ContentProviderOperation
                            .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)))
                            .build();
                    cpo.add(deleteOp);

                    break;

                default:
                    syncResult.stats.numIoExceptions++;
                    Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine());
                }
            }
            syncStatuses.put(pubUri, ss);
        } // for cursor

        if (cpo.size() > 0) {
            final ContentProviderResult[] results = provider.applyBatch(cpo);

            for (final ContentProviderResult result : results) {
                if (result.count != 1) {
                    throw new SyncException("Error deleting item");
                }
            }
        }

    } finally {
        c.close();
    }

    syncStatuses.clear();

    mLastUpdated.markUpdated(toSync);

    return true;
}

From source file:report.mainReport.java

public static LinkedList createTemporaryTable(Connection c, Statement s, String account) {
    ResultSet rs = null;//from w  w  w.  java2  s  .  c om
    boolean flag, proximite;
    boolean first = true;
    boolean topwrite = true;
    boolean statuslast = true;
    String devIDlast = "";
    String acIDlast = "";
    Timestamp dateEVlast = null;
    double latitudelast = 0;
    double longitudelast = 0;
    double odometerKMlast = 0;
    double odometerOffsetKMlast = 0;
    int headinglast = 0;
    double vitesselast = 0;
    int statusCodelast = -1;
    int nbevt = 0;
    int duree = 0;
    int i = 0;
    int nbrDevice = 0;

    formatSymbols.setDecimalSeparator('.');
    DecimalFormat dec = new DecimalFormat("#00.000000", formatSymbols);
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    Date dateBefore1Days = cal.getTime();
    //System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(dateBefore1Days));
    date_trt = new SimpleDateFormat("yyyy-MM-dd").format(dateBefore1Days);
    String date_fin = date_trt + " 23:59:59";
    date_trt = date_trt + " 00:00:00";
    LinkedList<Events> eventsList = new LinkedList<Events>();

    StringBuffer sb = new StringBuffer();
    //String sentence = "CREATE TEMPORARY TABLE datatmpEvt( tmpid int NOT NULL AUTO_INCREMENT, accountID varchar(45), deviceID varchar(45), dateEvt Timestamp, lat double, lon double, speed int, tmps int, first boolean, odometerKM double, odometerOffsetKM double, statusCode int, deviceSpeedLimit int,PRIMARY KEY(tmpid), INDEX(tmpid));";
    try {
        Statement st = c.createStatement();
        //s.executeUpdate(sentence);
        String sql = "SELECT count(*) as nbrDevice from Device WHERE accountID='" + account + "';";
        ResultSet rs1 = st.executeQuery(sql);
        if (rs1.next()) {
            nbrDevice = rs1.getObject("nbrDevice") != null ? rs1.getInt("nbrDevice") : null;
            deviceID = new String[nbrDevice];
            deviceSpeedLimit = new String[nbrDevice];
            sql = "SELECT accountID, deviceID, speedLimitKPH from Device WHERE accountID='" + account + "';";
            ResultSet rs2 = st.executeQuery(sql);
            for (flag = rs2.next(); flag; flag = rs2.next()) {
                deviceID[i] = rs2.getString("deviceID");
                deviceSpeedLimit[i] = rs2.getString("speedLimitKPH");
                //System.out.println(rs2.getString("accountID") + " " + deviceID[i]+" Vitesse limite:"+deviceSpeedLimit[i]+"kms/h");
                i++;
            }
            //String sql = "SELECT accountID, FROM_UNIXTIME(timestamp) as timestamp, deviceID, latitude, longitude, speedKPH FROM EventData WHERE accountID='telo' and deviceID='telo1' and DATE_FORMAT(FROM_UNIXTIME(timestamp),'%y-%m-%d') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 day),'%y-%m-%d') order by deviceID,timestamp;";
            //DATE_FORMAT(NOW(),'%y-%m-%d')
            sql = "SELECT accountID, FROM_UNIXTIME(timestamp) as timestamp, deviceID, latitude, longitude, speedKPH, odometerKM, odometerOffsetKM, statusCode, heading FROM EventData WHERE accountID='"
                    + account + "' and longitude <> 0.0 and FROM_UNIXTIME(timestamp) >= '" + date_trt
                    + "' and FROM_UNIXTIME(timestamp) <= '" + date_fin + "' order by deviceID,timestamp;";
            System.out.println(sql);
            rs = st.executeQuery(sql);
            // lecture premier enregistrement
            if (rs.next()) {
                acIDlast = rs.getObject("accountID") != null ? rs.getString("accountID") : null;
                devIDlast = rs.getObject("accountID") != null ? rs.getString("deviceID") : null;
                dateEVlast = rs.getTimestamp("timestamp");
                latitudelast = rs.getObject("latitude") != null ? rs.getDouble("latitude") : null;
                longitudelast = rs.getObject("longitude") != null ? rs.getDouble("longitude") : null;
                vitesselast = rs.getObject("speedKPH") != null ? rs.getInt("speedKPH") : null;
                statusCodelast = rs.getObject("statusCode") != null ? rs.getInt("statusCode") : null;
                //vitesselast = 0.;
                odometerKMlast = rs.getObject("odometerKM") != null ? rs.getDouble("odometerKM") : null;
                odometerOffsetKMlast = rs.getObject("odometerOffsetKM") != null
                        ? rs.getDouble("odometerOffsetKM")
                        : null;
                int statusCode = rs.getObject("statusCode") != null ? rs.getInt("statusCode") : null;
                headinglast = rs.getObject("heading") != null ? rs.getInt("heading") : 0;
                statuslast = true;
                int speedLimit = 0;
                for (int id = 0; id < nbrDevice; id++) {
                    if (devIDlast.equalsIgnoreCase(deviceID[id])) {
                        speedLimit = Integer.parseInt(deviceSpeedLimit[id]);
                        id = nbrDevice;
                    } else
                        speedLimit = 0;

                }
                eventsList.add(new Events(acIDlast, devIDlast, latitudelast, longitudelast, vitesselast,
                        dateEVlast, odometerKMlast, odometerOffsetKMlast, statusCode, speedLimit, headinglast));
                nbevt++;
                //Events evt = (Events) eventsList.get(0);
                //System.out.println(evt.getAccountID() + " " + evt.getDeviceID() + " " + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(evt.getDateEvt()) + " " + dec.format(evt.getLatitude()) + " "+ dec.format(evt.getLongitude()) + " " + evt.getSpeed() + " " + evt.getOdometerKM() + " " + evt.getSpeedMax() + " "+evt.getStatusCode());

                for (flag = rs.next(); flag; flag = rs.next()) {
                    String acID = rs.getObject("accountID") != null ? rs.getString("accountID") : null;
                    String devID = rs.getObject("accountID") != null ? rs.getString("deviceID") : null;
                    Timestamp dateEV = rs.getTimestamp("timestamp");
                    double latitude = rs.getObject("latitude") != null ? rs.getDouble("latitude") : null;
                    double longitude = rs.getObject("longitude") != null ? rs.getDouble("longitude") : null;
                    double vitesse = rs.getObject("speedKPH") != null ? rs.getInt("speedKPH") : null;
                    double odometerKM = rs.getObject("odometerKM") != null ? rs.getDouble("odometerKM") : null;
                    double odometerOffsetKM = rs.getObject("odometerOffsetKM") != null
                            ? rs.getDouble("odometerOffsetKM")
                            : null;
                    statusCode = rs.getObject("statusCode") != null ? rs.getInt("statusCode") : null;
                    int heading = rs.getObject("heading") != null ? rs.getInt("heading") : 0;
                    //System.out.println(acID + " " + devID + " " + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(dateEV) + " " + latitude + " "+ longitude + " " + vitesse);
                    //proximite = calculProx(latitude, longitude, latitudelast, longitudelast);
                    for (int id = 0; id < nbrDevice; id++) {
                        if (devIDlast.equalsIgnoreCase(deviceID[id])) {
                            speedLimit = Integer.parseInt(deviceSpeedLimit[id]);
                            id = nbrDevice;
                        } else
                            speedLimit = 0;

                    }
                    if (devIDlast.equalsIgnoreCase(devID)) {
                        /*if (vitesse == 0.0 && vitesselast == 0.0 && (odometerKM - odometerKMlast) < 1){
                        } 
                        else*/ {
                            if (INTERPOLATION) {
                                long diff = dateEV.getTime() - dateEVlast.getTime();
                                duree = (int) diff / 1000;
                                if (duree > 120) {
                                    eventsList = addpointsList(acID, devID, eventsList, latitude, longitude,
                                            dateEV, vitesse, odometerKM, odometerOffsetKM, statusCode,
                                            speedLimit, heading);
                                    nbevt++;
                                } else {
                                    eventsList.add(new Events(acID, devID, latitude, longitude, vitesse, dateEV,
                                            odometerKM, odometerOffsetKM, statusCode, speedLimit, heading));
                                    nbevt++;
                                    //evt = (Events) eventsList.get(eventsList.size()-1);
                                    //System.out.println(evt.getAccountID() + " " + evt.getDeviceID() + " " + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(evt.getDateEvt()) + " " + dec.format(evt.getLatitude()) + " "+ dec.format(evt.getLongitude()) + " " + evt.getSpeed() + " " + evt.getOdometerKM() + " " + evt.getSpeedMax() + " "+evt.getStatusCode());
                                }
                            } else {
                                eventsList.add(new Events(acID, devID, latitude, longitude, vitesse, dateEV,
                                        odometerKM, odometerOffsetKM, statusCode, speedLimit, heading));
                                nbevt++;
                            }
                            if (vitesse == 0.0 && vitesselast == 0.0) {

                            } else {
                                devIDlast = devID;
                                acIDlast = acID;
                                dateEVlast = dateEV;
                                latitudelast = latitude;
                                longitudelast = longitude;
                                vitesselast = vitesse;
                                odometerKMlast = odometerKM;
                                odometerOffsetKMlast = odometerOffsetKM;
                                statusCodelast = statusCode;
                                headinglast = heading;
                            }
                        }
                    } else {
                        eventsList.add(new Events(acID, devID, latitude, longitude, vitesse, dateEV, odometerKM,
                                odometerOffsetKM, statusCode, speedLimit, heading));
                        devIDlast = devID;
                        acIDlast = acID;
                        dateEVlast = dateEV;
                        latitudelast = latitude;
                        longitudelast = longitude;
                        vitesselast = vitesse;
                        odometerKMlast = odometerKM;
                        odometerOffsetKMlast = odometerOffsetKM;
                        statusCodelast = statusCode;
                        headinglast = heading;
                        //evt = (Events) eventsList.get(eventsList.size()-1);
                        //System.out.println(evt.getAccountID() + " " + evt.getDeviceID() + " " + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(evt.getDateEvt()) + " " + dec.format(evt.getLatitude()) + " "+ dec.format(evt.getLongitude()) + " " + evt.getSpeed() + " " + evt.getOdometerKM() + " " + evt.getSpeedMax() + " "+evt.getStatusCode());
                    }

                    /*if (devIDlast.equalsIgnoreCase(devID) && vitesse < 1 && vitesselast < 1) {
                       topwrite = false;
                    }
                    else {   
                       long diff = dateEV.getTime() - dateEVlast.getTime() ;
                       duree = (int) diff / 1000;
                       if (devIDlast.equalsIgnoreCase(devID)) {
                    if (statuslast) { 
                       first = true;
                       duree = 0;
                    }
                    statuslast = false;
                       }
                       else {
                    statuslast = true;
                    duree = 0;
                       }
                    if (first) { 
                       duree = 0;
                       //vitesselast = 0;
                    }
                    for(int id=0 ;id < nbrDevice;id++){
                       if (devIDlast.equalsIgnoreCase(deviceID[id])){
                          speedLimit = Integer.parseInt(deviceSpeedLimit[id]);
                          id = nbrDevice;
                       } else speedLimit = 0;
                                  
                    }
                         sentence = "INSERT INTO datatmpEvt(accountID, deviceID, dateEvt, lat, lon, speed, tmps, first, odometerKM, odometerOffsetKM, statusCode, deviceSpeedLimit) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                         PreparedStatement pstmt = c.prepareStatement(sentence);
                     pstmt.setString(1, acIDlast);
                     pstmt.setString(2, devIDlast);
                     pstmt.setTimestamp(3, dateEVlast);
                     pstmt.setDouble(4, latitudelast);
                     pstmt.setDouble(5, longitudelast);
                     pstmt.setDouble(6, vitesselast);
                     pstmt.setInt(7, duree);
                     pstmt.setBoolean(8, first);
                     pstmt.setDouble(9, odometerKMlast);
                     pstmt.setDouble(10, odometerOffsetKMlast);
                     pstmt.setInt(11, statusCodelast);
                     pstmt.setInt(12, speedLimit);
                    pstmt.executeUpdate();
                         nbevt++;
                            
                         devIDlast = devID;
                         acIDlast = acID;
                    dateEVlast = dateEV;
                    latitudelast = latitude;
                    longitudelast = longitude;
                    vitesselast = vitesse;
                    odometerKMlast = odometerKM;
                    odometerOffsetKMlast = odometerOffsetKM;
                    statusCodelast = statusCode;
                    first = false;
                    }*/
                }
                /*if (topwrite){
                   for(int id=0 ;id < nbrDevice;id++){
                 if (devIDlast.equalsIgnoreCase(deviceID[id])){
                    speedLimit = Integer.parseInt(deviceSpeedLimit[id]);
                    id = nbrDevice;
                 } else speedLimit = 0;
                            
                   }
                sentence = "INSERT INTO datatmpEvt(accountID, deviceID, dateEvt, lat, lon, speed, tmps, first, odometerKM, odometerOffsetKM, statusCode, deviceSpeedLimit) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                PreparedStatement pstmt = c.prepareStatement(sentence);
                 pstmt.setString(1, acIDlast);
                 pstmt.setString(2, devIDlast);
                 pstmt.setTimestamp(3, dateEVlast);
                 pstmt.setDouble(4, latitudelast);
                 pstmt.setDouble(5, longitudelast);
                 pstmt.setDouble(6, 0.0D);
                 pstmt.setInt(7, 0);
                 pstmt.setBoolean(8, first);
                 pstmt.setDouble(9, odometerKMlast);
                 pstmt.setDouble(10, odometerOffsetKMlast);
                  pstmt.setInt(11, statusCodelast);
                  pstmt.setInt(12, speedLimit);
                 pstmt.executeUpdate();
                nbevt++;
                }*/
            }
            rs2.close();
        }
        rs1.close();
        rs.close();

        for (int j = 0; j < eventsList.size(); j++) {
            Events evt = (Events) eventsList.get(j);
            System.out.println(evt.getAccountID() + " " + evt.getDeviceID() + " "
                    + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(evt.getDateEvt()) + " "
                    + dec.format(evt.getLatitude()) + " " + dec.format(evt.getLongitude()) + " "
                    + evt.getSpeed() + " " + evt.getOdometerKM() + " " + evt.getSpeedMax() + " "
                    + evt.getStatusCode() + " " + evt.getHeading());

        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    System.out.println("Chargement de la table termin. Nb=" + nbevt);
    return eventsList;
}