Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

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

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:org.ejbca.core.model.ra.raadmin.EndEntityProfile.java

private void decrementFieldnumber(final int parameter) {
    @SuppressWarnings("unchecked")
    final ArrayList<Integer> numberarray = (ArrayList<Integer>) data.get(NUMBERARRAY);
    numberarray.set(parameter, Integer.valueOf(numberarray.get(parameter).intValue() - 1));
}

From source file:com.glaf.core.config.Configuration.java

private void loadResources(Properties properties, ArrayList<Resource> resources, boolean quiet) {
    if (loadDefaults) {
        for (String resource : defaultResources) {
            loadResource(properties, new Resource(resource), quiet);
        }/*  w  ww.  j a  v  a2  s .  co m*/
    }

    for (int i = 0; i < resources.size(); i++) {
        Resource ret = loadResource(properties, resources.get(i), quiet);
        if (ret != null) {
            resources.set(i, ret);
        }
    }
}

From source file:de.ingrid.portal.portlets.SearchResultPortlet.java

public void doView(javax.portlet.RenderRequest request, javax.portlet.RenderResponse response)
        throws PortletException, IOException {
    Context context = getContext(request);
    IngridResourceBundle messages = new IngridResourceBundle(
            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());
    context.put("MESSAGES", messages);
    context.put("Codelists", CodeListServiceFactory.instance());
    context.put("enableFacete",
            PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_ENABLE_SEARCH_FACETE, false));

    // add request language, used to localize the map client
    context.put("languageCode", request.getLocale().getLanguage());

    PortletSession ps = request.getPortletSession();

    if (request.getParameter("filter") != null) {
        if (request.getParameter("filter").equals("domain")) {
            context.put("isFilterDomain", true);
        }//from   w w w  .j  a v a  2  s  . co  m
    }
    // ----------------------------------
    // check for passed RENDER PARAMETERS (for bookmarking) and
    // ADAPT OUR PERMANENT STATE VIA MESSAGES
    // ----------------------------------
    // starthit RANKED

    // WHEN NO GROUPING !!!
    String reqParam = null;

    int rankedStartHit = 0;
    try {
        reqParam = request.getParameter(Settings.PARAM_STARTHIT_RANKED);
        if (SearchState.adaptSearchState(request, Settings.PARAM_STARTHIT_RANKED, reqParam)) {
            rankedStartHit = (new Integer(reqParam)).intValue();
        }
    } catch (Exception ex) {
        if (log.isErrorEnabled()) {
            log.error(
                    "Problems parsing RANKED starthit from render request, set RANKED starthit to 0 ! reqParam="
                            + reqParam,
                    ex);
        }
    }

    // WHEN GROUPING !!!
    // get the current page number, default to 1
    int currentSelectorPage = 1;
    try {
        reqParam = request.getParameter(Settings.PARAM_CURRENT_SELECTOR_PAGE);
        if (SearchState.adaptSearchState(request, Settings.PARAM_CURRENT_SELECTOR_PAGE, reqParam)) {
            currentSelectorPage = new Integer(reqParam).intValue();
        }
    } catch (Exception ex) {
        if (log.isErrorEnabled()) {
            log.error(
                    "Problems parsing currentSelectorPage from render request, set currentSelectorPage to 1 ! reqParam="
                            + reqParam,
                    ex);
        }
    }

    // starthit UNRANKED

    // NO GROUPING !!!
    // Do we need to read unrankedStartHit, is passed from navi when not grouped but UNRANKED SEARCH IS ALWAYS GROUPED !!!
    int unrankedStartHit = 0;
    try {
        reqParam = request.getParameter(Settings.PARAM_STARTHIT_UNRANKED);
        if (SearchState.adaptSearchState(request, Settings.PARAM_STARTHIT_UNRANKED, reqParam)) {
            unrankedStartHit = (new Integer(reqParam)).intValue();
        }
    } catch (Exception ex) {
        if (log.isErrorEnabled()) {
            log.error(
                    "Problems parsing UNRANKED starthit from render request, set UNRANKED starthit to 0 ! reqParam="
                            + reqParam,
                    ex);
        }
    }

    // GROUPING ONLY !!!
    // UNRANKED SEARCH IS ALWAYS GROUPED !!!
    // get the current page number, default to 1
    int currentSelectorPageUnranked = 1;
    try {
        reqParam = request.getParameter(Settings.PARAM_CURRENT_SELECTOR_PAGE_UNRANKED);
        if (SearchState.adaptSearchState(request, Settings.PARAM_CURRENT_SELECTOR_PAGE_UNRANKED, reqParam)) {
            currentSelectorPageUnranked = new Integer(reqParam).intValue();
        }
    } catch (Exception ex) {
        if (log.isErrorEnabled()) {
            log.error(
                    "Problems parsing currentSelectorPageUnranked from render request, set currentSelectorPageUnranked to 1 ! reqParam="
                            + reqParam,
                    ex);
        }
    }

    // indicates whether we do a query or we read results from cache
    String queryType = (String) SearchState.getSearchStateObject(request, Settings.MSG_QUERY_EXECUTION_TYPE);
    if (queryType == null) {
        queryType = "";
    }

    // get the filter from REQUEST, not search state ! -> so back button works !
    // ALSO ADAPT SEARCH STATE, so following steps (query pre processor) work !
    String filter = request.getParameter(Settings.PARAM_FILTER);
    if (filter != null && filter.length() == 0) {
        filter = null;
    }
    SearchState.adaptSearchState(request, Settings.PARAM_FILTER, filter);
    String filterSubject = request.getParameter(Settings.PARAM_SUBJECT);
    SearchState.adaptSearchState(request, Settings.PARAM_SUBJECT, filterSubject);

    // set filter params into context for filter display
    if (filter != null) {
        context.put("filteredBy", filter);
        if (filter.equals(Settings.PARAMV_GROUPING_PARTNER)) {
            context.put("filterSubject",
                    UtilsSearch.mapResultValue(Settings.RESULT_KEY_PARTNER, filterSubject, null));
        } else if (filter.equals(Settings.PARAMV_GROUPING_PROVIDER)) {
            context.put("filterSubject",
                    UtilsSearch.mapResultValue(Settings.RESULT_KEY_PROVIDER, filterSubject, null));
        } else if (filter.equals(Settings.PARAMV_GROUPING_PLUG_ID)) {
            context.put("filterSubject",
                    UtilsSearch.mapResultValue(Settings.RESULT_KEY_PLUG_ID, filterSubject, null));
        } else if (filter.equals(Settings.PARAMV_GROUPING_DOMAIN)) {
            String[] keyValuePair = UtilsSearch.getDomainKeyValuePair(filterSubject);
            String domainKey = keyValuePair[0];
            String domainValue = keyValuePair[1];
            // domain can be plugid or site or ...
            // we extract the according value from our subject
            if (domainKey.equals(Settings.QFIELD_PLUG_ID)) {
                domainValue = UtilsSearch.mapResultValue(Settings.RESULT_KEY_PLUG_ID, domainValue, null);
            }
            context.put("filterSubject", domainValue);
        }
    }

    // datasource from state (set in SimpleSearch Portlet)
    String selectedDS = SearchState.getSearchStateObjectAsString(request, Settings.PARAM_DATASOURCE);

    // IngridQuery from state  (set in SimpleSearch Portlet)
    IngridQuery query = (IngridQuery) SearchState.getSearchStateObject(request, Settings.MSG_QUERY);

    // change datasource dependent from query input
    selectedDS = UtilsSearch.determineFinalPortalDatasource(selectedDS, query);

    // ----------------------------------
    // set initial view template
    // ----------------------------------

    // if no query set display "nothing"
    if (query == null) {
        setDefaultViewPage(TEMPLATE_NO_QUERY_SET);
        super.doView(request, response);
        return;
    }

    // selected data source ("Umweltinfo", Adressen" or "Forschungsprojekte")
    if (selectedDS == null) {
        selectedDS = Settings.SEARCH_INITIAL_DATASOURCE;
    }
    if (selectedDS.equals(Settings.PARAMV_DATASOURCE_ADDRESS)) {
        setDefaultViewPage(TEMPLATE_RESULT_ADDRESS);
    } else {
        setDefaultViewPage(TEMPLATE_RESULT);

        // default: right column IS grouped (by plugid)
        // set in context e.g. to show grouped navigation
        context.put("grouping_right", new Boolean(true));

        if (filter != null) {
            // set one column result template if "Zeige alle ..." of plug or domain
            if (filter.equals(Settings.PARAMV_GROUPING_PLUG_ID)
                    || filter.equals(Settings.PARAMV_GROUPING_DOMAIN)) {
                setDefaultViewPage(TEMPLATE_RESULT_FILTERED_ONECOLUMN);
                // only one column to render we switch off grouping_right to show ungrouped navigation !
                context.put("grouping_right", new Boolean(false));
            }
        }
    }
    // check whether right column is switched OFF and set according context flag
    boolean rightColumnDisabled = !PortalConfig.getInstance()
            .getBoolean(PortalConfig.PORTAL_ENABLE_SEARCH_RESULTS_UNRANKED, true);
    context.put("RIGHT_COLUMN_DISABLED", rightColumnDisabled);

    String currentView = getDefaultViewPage();

    // ----------------------------------
    // business logic
    // ----------------------------------

    // check for Javascript
    boolean hasJavaScript = Utils.isJavaScriptEnabled(request);

    // determine whether we have to render only one result column
    boolean renderResultColumnRanked = true;
    boolean renderResultColumnUnranked = true;
    reqParam = request.getParameter("js_ranked");
    // finally disable query for right column if switched OFF !
    if (rightColumnDisabled) {
        renderResultColumnUnranked = false;
    }

    // create threaded query controller
    ThreadedQueryController controller = new ThreadedQueryController();
    controller.setTimeout(PortalConfig.getInstance().getInt(PortalConfig.QUERY_TIMEOUT_THREADED, 120000));

    QueryDescriptor qd = null;

    // store query in session
    UtilsSearch.addQueryToHistory(request);

    // RANKED
    IngridHitsWrapper rankedHits = null;
    if (renderResultColumnRanked) {
        if (reqParam == null) {
            // check if query must be executed
            if (queryType.equals(Settings.MSGV_NO_QUERY) || queryType.equals(Settings.MSGV_UNRANKED_QUERY)) {
                rankedHits = (IngridHitsWrapper) SearchState.getSearchStateObject(request,
                        Settings.MSG_SEARCH_RESULT_RANKED);
                if (log.isDebugEnabled()) {
                    log.debug("Read RANKED hits from CACHE !!! rankedHits=" + rankedHits);
                }
            } else {
                // process query, create QueryDescriptor
                qd = QueryPreProcessor.createRankedQueryDescriptor(request);
                if (qd != null) {
                    controller.addQuery("ranked", qd);
                    SearchState.resetSearchStateObject(request, Settings.MSG_SEARCH_FINISHED_RANKED);
                }
            }
        }
    } else {
        if (queryType.equals(Settings.MSGV_UNRANKED_QUERY)) {
            if (ps.getAttribute("isPagingUnranked") != null
                    && ps.getAttribute("isPagingUnranked").equals(currentSelectorPageUnranked + "")) {
                ps.removeAttribute("isPagingUnranked");
                rankedHits = (IngridHitsWrapper) SearchState.getSearchStateObject(request,
                        Settings.MSG_SEARCH_RESULT_RANKED);
                if (log.isDebugEnabled()) {
                    log.debug("Read RANKED hits from CACHE !!! rankedHits=" + rankedHits);
                }
            } else {
                // process query, create QueryDescriptor
                qd = QueryPreProcessor.createRankedQueryDescriptor(request);
                if (qd != null) {
                    controller.addQuery("ranked", qd);
                    SearchState.resetSearchStateObject(request, Settings.MSG_SEARCH_FINISHED_RANKED);
                }
            }
        }
    }

    // UNRANKED
    IngridHitsWrapper unrankedHits = null;
    if (renderResultColumnUnranked) {
        if (reqParam != null && reqParam.equals("false") || !hasJavaScript) {
            if (!currentView.equals(TEMPLATE_RESULT_ADDRESS)) {
                // check if query must be executed
                if (queryType.equals(Settings.MSGV_NO_QUERY) || queryType.equals(Settings.MSGV_RANKED_QUERY)) {
                    if (!currentView.equals(TEMPLATE_RESULT_FILTERED_ONECOLUMN)) {
                        unrankedHits = (IngridHitsWrapper) SearchState.getSearchStateObject(request,
                                Settings.MSG_SEARCH_RESULT_UNRANKED);
                        if (log.isDebugEnabled()) {
                            log.debug("Read UNRANKED hits from CACHE !!!! unrankedHits=" + unrankedHits);
                        }
                    } else {
                        // process query, create QueryDescriptor
                        qd = QueryPreProcessor.createUnrankedQueryDescriptor(request);
                        if (qd != null) {
                            controller.addQuery("unranked", qd);
                            SearchState.resetSearchStateObject(request, Settings.MSG_SEARCH_FINISHED_UNRANKED);
                        }
                    }
                } else {
                    // process query, create QueryDescriptor
                    qd = QueryPreProcessor.createUnrankedQueryDescriptor(request);
                    if (qd != null) {
                        controller.addQuery("unranked", qd);
                        SearchState.resetSearchStateObject(request, Settings.MSG_SEARCH_FINISHED_UNRANKED);
                    }
                }
            }
        } else {
            if (queryType.equals(Settings.MSGV_RANKED_QUERY)) {
                if (ps.getAttribute("isPagingRanked") != null
                        && ps.getAttribute("isPagingRanked").equals(currentSelectorPage + "")) {
                    ps.removeAttribute("isPagingRanked");
                    unrankedHits = (IngridHitsWrapper) SearchState.getSearchStateObject(request,
                            Settings.MSG_SEARCH_RESULT_UNRANKED);
                    if (log.isDebugEnabled()) {
                        log.debug("Read UNRANKED hits from CACHE !!!! unrankedHits=" + unrankedHits);
                    }
                } else {
                    // process query, create QueryDescriptor
                    qd = QueryPreProcessor.createUnrankedQueryDescriptor(request);
                    if (qd != null) {
                        controller.addQuery("unranked", qd);
                        SearchState.resetSearchStateObject(request, Settings.MSG_SEARCH_FINISHED_UNRANKED);
                    }
                }
            }
        }
    }

    // get possible changes AFTER PREPROCESSING QUERY !!!

    // Grouping may have changed !
    String grouping = (String) SearchState.getSearchStateObject(request, Settings.PARAM_GROUPING);

    // fire query, post process results
    boolean rankedColumnHasMoreGroupedPages = true;
    if (controller.hasQueries()) {
        // fire queries
        HashMap results = controller.search();

        // check for zero results
        // log the result to the resource logger
        Iterator it = results.keySet().iterator();
        boolean noResults = true;
        String queryTypes = "";
        while (it.hasNext()) {
            Object key = it.next();
            if (queryTypes.length() > 0) {
                queryTypes = queryTypes.concat(",");
            } else {
                queryTypes = queryTypes.concat(key.toString());
            }
            IngridHitsWrapper hits = (IngridHitsWrapper) results.get(key);
            if (hits != null && hits.length() > 0) {
                noResults = false;
                break;
            }
        }
        if (noResults) {

            String url = PortalConfig.getInstance().getString(PortalConfig.PORTAL_LOGGER_RESOURCE);
            if (url != null) {
                String queryString = SearchState.getSearchStateObjectAsString(request,
                        Settings.PARAM_QUERY_STRING);
                HttpMethod method = null;
                try {
                    url = url.concat("?code=NO_RESULTS_FOR_QUERY&q=")
                            .concat(URLEncoder.encode(queryString, "UTF-8")).concat("&qtypes=")
                            .concat(URLEncoder.encode(queryTypes, "UTF-8"));
                    method = new GetMethod(url);
                    method.setFollowRedirects(true);
                    client.executeMethod(method);
                } catch (Throwable t) {
                    if (log.isErrorEnabled()) {
                        log.error("Cannot make connection to logger resource: ".concat(url), t);
                    }
                } finally {
                    if (method != null) {
                        try {
                            method.releaseConnection();
                        } catch (Throwable t) {
                            if (log.isErrorEnabled()) {
                                log.error("Cannot close connection to logger resource: ".concat(url), t);
                            }
                        }
                    }
                }
            }
        }

        // post process ranked hits if exists
        if (results.containsKey("ranked")) {
            rankedHits = QueryResultPostProcessor.processRankedHits((IngridHitsWrapper) results.get("ranked"),
                    selectedDS);
            SearchState.adaptSearchState(request, Settings.MSG_SEARCH_RESULT_RANKED, rankedHits);
            SearchState.adaptSearchState(request, Settings.MSG_SEARCH_FINISHED_RANKED, Settings.MSGV_TRUE);

            // GROUPING ONLY !!!
            if (grouping != null && !grouping.equals(IngridQuery.GROUPED_OFF)) {
                // get the grouping starthits history from session
                // create and initialize if not exists
                // NOTICE: when grouping by domain the navigation is like ungrouped navigation, so multiple pages are rendered !
                try {
                    ArrayList groupedStartHits = (ArrayList) SearchState.getSearchStateObject(request,
                            Settings.PARAM_GROUPING_STARTHITS);
                    if (groupedStartHits == null) {
                        groupedStartHits = new ArrayList();
                        SearchState.adaptSearchState(request, Settings.PARAM_GROUPING_STARTHITS,
                                groupedStartHits);
                    }
                    // set starthit of NEXT page ! ensure correct size of Array ! Notice: currentSelectorPage is 1 for first page !
                    while (currentSelectorPage >= groupedStartHits.size()) {
                        groupedStartHits.add(new Integer(0));
                    }
                    // set start hit for next page (grouping)
                    int nextStartHit = rankedHits.getGoupedHitsLength();
                    groupedStartHits.set(currentSelectorPage, new Integer(nextStartHit));

                    // check whether there are more pages for grouped hits ! this is done due to former Bug in Backend !
                    // still necessary ? well, these former checks don't damage anything ...
                    if (rankedHits.length() <= rankedHits.getGoupedHitsLength()) {
                        // total number of hits (ungrouped) already processed -> no more pages
                        rankedColumnHasMoreGroupedPages = false;
                    } else {
                        int currentStartHit = ((Integer) groupedStartHits.get(currentSelectorPage - 1))
                                .intValue();
                        if (nextStartHit == currentStartHit) {
                            // start hit for next page same as start hit for current page -> no more pages
                            rankedColumnHasMoreGroupedPages = false;
                        }
                    }
                } catch (Exception ex) {
                    if (log.isInfoEnabled()) {
                        log.info("Problems processing grouping starthits RANKED", ex);
                    }
                }
            }

        }
        // post process unranked hits if exists
        if (results.containsKey("unranked")) {
            unrankedHits = QueryResultPostProcessor
                    .processUnrankedHits((IngridHitsWrapper) results.get("unranked"), selectedDS);
            SearchState.adaptSearchState(request, Settings.MSG_SEARCH_RESULT_UNRANKED, unrankedHits);
            SearchState.adaptSearchState(request, Settings.MSG_SEARCH_FINISHED_UNRANKED, Settings.MSGV_TRUE);
            // get the grouping starthits history from session
            // create and initialize if not exists
            try {
                ArrayList groupedStartHits = (ArrayList) SearchState.getSearchStateObject(request,
                        Settings.PARAM_GROUPING_STARTHITS_UNRANKED);
                if (groupedStartHits == null || unrankedHits == null) {
                    groupedStartHits = new ArrayList();
                    groupedStartHits.add(new Integer(0));
                    SearchState.adaptSearchState(request, Settings.PARAM_GROUPING_STARTHITS_UNRANKED,
                            groupedStartHits);
                } else {
                    // set start hit for next page (grouping)
                    int nextStartHit = unrankedHits.getGoupedHitsLength();
                    groupedStartHits.add(currentSelectorPageUnranked, new Integer(nextStartHit));
                }
            } catch (Exception ex) {
                if (log.isDebugEnabled()) {
                    log.debug("Problems processing grouping starthits UNRANKED", ex);
                }
                if (log.isInfoEnabled()) {
                    log.info(
                            "Problems processing grouping starthits UNRANKED. switch to debug level to get the exception logged.");
                }
            }
        }
    }

    int totalNumberOfRankedHits = 0;
    if (rankedHits != null) {
        totalNumberOfRankedHits = (int) rankedHits.length();
    }
    // adapt settings of ranked page navigation
    HashMap rankedPageNavigation = UtilsSearch.getPageNavigation(rankedStartHit,
            Settings.SEARCH_RANKED_HITS_PER_PAGE, totalNumberOfRankedHits,
            Settings.SEARCH_RANKED_NUM_PAGES_TO_SELECT);

    int totalNumberOfUnrankedHits = 0;
    if (unrankedHits != null) {
        if (filter != null && filter.equals(Settings.RESULT_KEY_PLUG_ID)) {
            totalNumberOfUnrankedHits = (int) unrankedHits.length();
        } else {
            totalNumberOfUnrankedHits = unrankedHits.getInVolvedPlugs();
        }
    }
    // adapt settings of unranked page navigation
    HashMap unrankedPageNavigation = UtilsSearch.getPageNavigation(unrankedStartHit,
            Settings.SEARCH_UNRANKED_HITS_PER_PAGE, totalNumberOfUnrankedHits,
            Settings.SEARCH_UNRANKED_NUM_PAGES_TO_SELECT);

    Object rankedSearchFinished = SearchState.getSearchStateObject(request,
            Settings.MSG_SEARCH_FINISHED_RANKED);
    Object unrankedSearchFinished = SearchState.getSearchStateObject(request,
            Settings.MSG_SEARCH_FINISHED_UNRANKED);
    /*
     // DON'T SHOW separate Template when no results ! This one is never displayed when JS is active and search is performed
     // initially (cause then always two columns are rendered (via iframes)). Only afterwards, e.g. when similar terms are
     // clicked, this template is displayed, causing changes of result content (when similar terms are displayed).
     // WE DON'T WANT TO CHANGE RESULTS CONTENT, WHEN SIMILAR TERMS ARE CKLICKED (DO we ???)
     if (rankedSearchFinished != null && unrankedSearchFinished != null && numberOfRankedHits == 0
     && numberOfUnrankedHits == 0 && (renderOneResultColumnUnranked && renderOneResultColumnRanked)
     && filter.length() == 0) {
     // query string will be displayed when no results !
     String queryString = SearchState.getSearchStateObjectAsString(request, Settings.PARAM_QUERY_STRING);
     context.put("queryString", queryString);
            
     setDefaultViewPage(TEMPLATE_NO_RESULT);
     super.doView(request, response);
     return;
     }
     */
    // ----------------------------------
    // prepare view
    // ----------------------------------

    // GROUPING
    // adapt page navigation for grouping in left column 
    if (renderResultColumnRanked) {
        if (grouping != null && !grouping.equals(IngridQuery.GROUPED_OFF)) {
            UtilsSearch.adaptRankedPageNavigationToGrouping(rankedPageNavigation, currentSelectorPage,
                    rankedColumnHasMoreGroupedPages, totalNumberOfRankedHits, request);

            if (grouping.equals(IngridQuery.GROUPED_BY_PARTNER)) {
                context.put("grouping", "partner");
            } else if (grouping.equals(IngridQuery.GROUPED_BY_ORGANISATION)) {
                context.put("grouping", "provider");
            } else if (grouping.equals(IngridQuery.GROUPED_BY_DATASOURCE)) {
                context.put("grouping", "domain");
            }
        }
    }
    // adapt page navigation for right column (always grouped)
    if (renderResultColumnUnranked) {
        unrankedPageNavigation.put(Settings.PARAM_CURRENT_SELECTOR_PAGE_UNRANKED,
                new Integer(currentSelectorPageUnranked));
        // check if we have more results to come
        if (unrankedHits != null) {
            int groupedHitsLength = unrankedHits.getGoupedHitsLength();
            if (groupedHitsLength > 0 && totalNumberOfUnrankedHits > 0) {
                if (totalNumberOfUnrankedHits <= groupedHitsLength) {
                    unrankedPageNavigation.put("selectorHasNextPage", new Boolean(false));
                } else {
                    unrankedPageNavigation.put("selectorHasNextPage", new Boolean(true));
                }
            }
        }
    }

    boolean showAdminContent = false;
    if (request.getUserPrincipal() != null) {
        showAdminContent = request.getUserPrincipal().getName().equals("admin");
    }

    // check for one column rendering
    if (reqParam != null) {
        // check if we have to render only the ranked column
        if (reqParam.equals("true")) {
            request.setAttribute(GenericServletPortlet.PARAM_VIEW_PAGE, TEMPLATE_RESULT_JS_RANKED);
            renderResultColumnUnranked = false;
        } else {
            request.setAttribute(GenericServletPortlet.PARAM_VIEW_PAGE, TEMPLATE_RESULT_JS_UNRANKED);
            renderResultColumnRanked = false;
        }
        // check for js enabled iframe rendering

    } else if (currentView.equals(TEMPLATE_RESULT_FILTERED_ONECOLUMN)) {
        if (filter.equals(Settings.PARAMV_GROUPING_PLUG_ID) && rankedHits == null) {
            renderResultColumnRanked = false;
            context.put("IS_RANKED", new Boolean(false));
        } else {
            // grouping by domain
            renderResultColumnUnranked = false;
            context.put("IS_RANKED", new Boolean(true));
        }

    } else if (currentView.equals(TEMPLATE_RESULT_ADDRESS)) {
        renderResultColumnUnranked = false;
        context.put("ds", request.getParameter("ds"));

        // check for js enabled iframe rendering
    } else if (hasJavaScript && queryType.equals(Settings.MSGV_NEW_QUERY)) {
        // if javascript and new query, set template to javascript enabled iframe template
        // exit method!!
        request.setAttribute(GenericServletPortlet.PARAM_VIEW_PAGE, TEMPLATE_RESULT_JS);

        context.put("ds", request.getParameter("ds"));

        if (rankedHits != null) {
            if (PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_ENABLE_SEARCH_FACETE, false)) {
                UtilsFacete.checkForExistingFacete((IngridHitsWrapper) rankedHits, request);
                UtilsFacete.setParamsToContext(request, context, true);
            }
        }

        context.put("adminContent", showAdminContent);
        context.put("rankedPageSelector", rankedPageNavigation);
        context.put("rankedResultList", rankedHits);
        context.put("rankedSearchFinished", rankedSearchFinished);
        context.put("unrankedResultUrl",
                response.encodeURL(((RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV))
                        .getRequest().getContextPath() + "/portal/search-result-js.psml"
                        + SearchState.getURLParamsMainSearch(request) + "&js_ranked=false"));
        super.doView(request, response);
        return;
    }

    context.put("adminContent", showAdminContent);
    context.put("rankedPageSelector", rankedPageNavigation);
    context.put("unrankedPageSelector", unrankedPageNavigation);
    if (rankedHits != null) {
        if (PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_ENABLE_SEARCH_FACETE, false)) {
            UtilsFacete.checkForExistingFacete((IngridHitsWrapper) rankedHits, request);
            UtilsFacete.setParamsToContext(request, context, true);
        }
    }
    context.put("rankedResultList", rankedHits);
    context.put("unrankedResultList", unrankedHits);
    context.put("rankedSearchFinished", rankedSearchFinished);
    context.put("unrankedSearchFinished", unrankedSearchFinished);
    //context.put("providerMap", getProviderMap());

    super.doView(request, response);
}

From source file:ffx.autoparm.Potential2.java

/**
 * <p>/* w  ww . ja v a  2 s  .co m*/
 * output_stats</p>
 */
public void output_stats() {
    ArrayList<Integer> natm = new ArrayList<Integer>();
    ArrayList<Double> rmsa = new ArrayList<Double>();
    ArrayList<Double> patm1 = new ArrayList<Double>();
    ArrayList<Double> patm2 = new ArrayList<Double>();
    Double xyz[] = new Double[3];
    double pot;
    double target;
    double a_pot = 0;
    double a_target = 0;
    double tave = 0;
    double uave = 0;
    double avgrms = 0;
    for (int i = 0; i < nAtoms; i++) {
        natm.add(0);
        rmsa.add(0.0);
        patm1.add(0.0);
        patm2.add(0.0);
    }
    int k;
    int npoints = target_grid[0].length;
    for (int i = 0; i < nSymm; i++) {
        for (int j = 0; j < npoints; j++) {
            xyz[0] = target_grid[i][j][0];
            xyz[1] = target_grid[i][j][1];
            xyz[2] = target_grid[i][j][2];
            pot = pme.potpoint(xyz);
            //System.out.println(pot);
            target = target_grid[i][j][3];
            a_pot += Math.abs(pot);
            a_target += Math.abs(target);
            tave += pot - target;
            uave += Math.abs(pot - target);
            k = ipgrid.get(j);
            natm.set(k, natm.get(k) + 1);
            patm1.set(k, patm1.get(k) + pot);
            patm2.set(k, patm2.get(k) + target);
            rmsa.set(k, rmsa.get(k) + Math.pow(pot - target, 2));
        }
    }
    for (int i = 0; i < nAtoms; i++) {
        patm1.set(i, patm1.get(i) / natm.get(i));
        patm2.set(i, patm2.get(i) / natm.get(i));
        rmsa.set(i, Math.sqrt(rmsa.get(i) / natm.get(i)));
    }
    a_pot = a_pot / npoints;
    a_target = a_target / npoints;
    tave = tave / npoints;
    uave = uave / npoints;
    avgrms = avgrms();
    System.out.println("\nAverage Electrostatic Potential over Atoms :\n (Kcal/mole per unit charge)\n");
    System.out.println("Atom \t Points \t Potential \t Target \t RMS Diff\n");
    for (int i = 0; i < nAtoms; i++) {
        System.out.printf("%d \t %d \t %12.6g \t %12.6g \t %12.6g\n", i + 1, natm.get(i), patm1.get(i),
                patm2.get(i), rmsa.get(i));
    }
    System.out.println("\nElectrostatic Potential over all Grid Points :\n");
    System.out.printf("Average Magnitude for Potential : \t\t %12.6g\n", a_pot);
    System.out.printf("Average Magnitude for Target : \t\t\t %12.6g\n", a_target);
    System.out.printf("Average Signed Potential Difference : \t\t %12.6g\n", tave);
    System.out.printf("Average Unsigned Potential Difference : \t %12.6g\n", uave);
    System.out.printf("Root Mean Square Potential Difference : \t %12.6g\n", avgrms);
    stats[0] = a_pot;
    stats[1] = a_target;
    stats[2] = tave;
    stats[3] = uave;
    stats[4] = avgrms;
}

From source file:org.apache.lucene.queryparser.classic.PreAnalyzedQueryParser.java

/***
 * Perform tokenization and term analysis using the Solr analyzers defined in the Schema. 
 * @param langCode /*w ww.j  a va  2 s  .  co m*/
 * @param rawContent 
 * @return
 * */
private ArrayList<String> getTokensArrayUsingFieldTypes(String langCode, String rawContent) {
    ArrayList<String> tokens = new ArrayList<String>();
    Boolean isPhrase = false;
    if ((rawContent.trim().startsWith("\"")) && (rawContent.trim().endsWith("\""))) {
        isPhrase = true;
    }
    try {
        // Build Solr field type based on language and get the respective analyzer
        String fieldTypeName = "text_" + langCode;
        FieldType fType = schema.getFieldTypeByName(fieldTypeName);
        //Analyzer an = fType.getAnalyzer();
        Analyzer an = fType.getQueryAnalyzer();

        // Apply the analyzer to the content
        TokenStream ts = null;
        ts = an.tokenStream("", new StringReader(rawContent));
        ts.reset();
        CharTermAttribute term = (CharTermAttribute) ts.getAttribute(CharTermAttribute.class);
        int termsCount = 0;
        while (ts.incrementToken()) { // For each detected token
            if ((termsCount == 0) && isPhrase) {
                tokens.add("\"" + term.toString()); // preserve initial quote
            } else {
                String tok = term.toString();
                if (rawContent.contains(tok + "*")) {// preserve trailing wildcard operator
                    tok += "*";
                }
                if (rawContent.contains("*" + tok)) {// preserve leading wildcard operator
                    tok = "*" + tok;
                }
                tokens.add(tok);
            }
            termsCount++;
        }
        if (isPhrase) { // Adding final quote to last term from phrase
            tokens.set(tokens.size() - 1, tokens.get(tokens.size() - 1) + "\"");
        }
        // Close token stream
        ts.end();
        ts.close();
    } catch (Exception e) {
        // TODO: handle exception
    }

    return tokens;
}

From source file:com.wildplot.android.ankistats.HourlyBreakdown.java

public boolean calculateBreakdown(int type) {
    mTitle = R.string.stats_breakdown;/*from w  ww.  j a va  2s.co  m*/
    mAxisTitles = new int[] { R.string.stats_time_of_day, R.string.stats_percentage_correct,
            R.string.stats_reviews };

    mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers };
    mColors = new int[] { R.color.stats_counts, R.color.stats_hours };

    mType = type;
    String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", "");

    if (lim.length() > 0) {
        lim = " and " + lim;
    }

    Calendar sd = GregorianCalendar.getInstance();
    sd.setTimeInMillis(mCollectionData.getCrt() * 1000);
    Calendar cal = Calendar.getInstance();
    TimeZone tz = TimeZone.getDefault();

    /* date formatter in local timezone */
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    sdf.setTimeZone(tz);

    /* print your timestamp and double check it's the date you expect */

    String localTime = sdf.format(new Date(mCollectionData.getCrt() * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?

    int pd = _periodDays();
    if (pd > 0) {
        lim += " and id > " + ((mCollectionData.getDayCutoff() - (86400 * pd)) * 1000);
    }

    int hourOfDay = sd.get(GregorianCalendar.HOUR_OF_DAY);
    long cutoff = mCollectionData.getDayCutoff();
    long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600;

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "select " + "23 - ((cast((" + cut + " - id/1000) / 3600.0 as int)) % 24) as hour, "
            + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() "
            + "from revlog where type in (0,1,2) " + lim + " "
            + "group by hour having count() > 30 order by hour";
    Log.d(AnkiStatsApplication.TAG,
            sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " breakdown query: " + query);
    try {
        cur = mAnkiDb.getDatabase().rawQuery(query, null);
        while (cur.moveToNext()) {
            list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) });
        }

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    //TODO adjust for breakdown, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    //        if (list.size() == 0 || list.get(0)[0] > 0) {
    //            list.add(0, new double[] { 0, 0, 0 });
    //        }
    //        if (num == -1 && list.size() < 2) {
    //            num = 31;
    //        }
    //        if (type != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) {
    //            list.add(new double[] { num, 0, 0 });
    //        } else if (type == Utils.TYPE_LIFE && list.size() < 2) {
    //            list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 });
    //        }

    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int intHour = (int) data[0];
        int hour = (intHour - 4) % 24;
        if (hour < 0)
            hour += 24;
        data[0] = hour;
        list.set(i, data);
    }
    Collections.sort(list, new Comparator<double[]>() {
        @Override
        public int compare(double[] s1, double[] s2) {
            if (s1[0] < s2[0])
                return -1;
            if (s1[0] > s2[0])
                return 1;
            return 0;
        }
    });

    mSeriesList = new double[4][list.size()];
    mPeak = 0.0;
    mMcount = 0.0;
    double minHour = Double.MAX_VALUE;
    double maxHour = 0;
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int hour = (int) data[0];

        //double hour = data[0];
        if (hour < minHour)
            minHour = hour;

        if (hour > maxHour)
            maxHour = hour;

        double pct = data[1];
        if (pct > mPeak)
            mPeak = pct;

        mSeriesList[0][i] = hour;
        mSeriesList[1][i] = pct;
        mSeriesList[2][i] = data[2];
        if (i == 0) {
            mSeriesList[3][i] = pct;
        } else {
            double prev = mSeriesList[3][i - 1];
            double diff = pct - prev;
            diff /= 3.0;
            diff = Math.round(diff * 10.0) / 10.0;

            mSeriesList[3][i] = prev + diff;
        }

        if (data[2] > mMcount)
            mMcount = data[2];
        if (mSeriesList[1][i] > mMaxCards)
            mMaxCards = (int) mSeriesList[1][i];
    }

    mMaxElements = (int) (maxHour - minHour);
    return list.size() > 0;
}

From source file:com.maxl.java.aips2sqlite.RealExpertInfo.java

/**
 * Extracts package info from Swissmedic package Excel file
 *//*from  w w  w .j  a va2 s .c  om*/
private void extractPackageInfo() {
    try {
        long startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.print("- Processing packages xlsx... ");
        // Load Swissmedic xls file         
        FileInputStream packages_file = new FileInputStream(Constants.FILE_PACKAGES_XLSX);
        // Get workbook instance for XLSX file (XSSF = Horrible SpreadSheet Format)
        XSSFWorkbook packages_workbook = new XSSFWorkbook(packages_file);
        // Get first sheet from workbook
        XSSFSheet packages_sheet = packages_workbook.getSheetAt(0);

        /*
        if (SHOW_LOGS)
           System.out.print("- Processing packages xls... ");
        // Load Swissmedic xls file         
        FileInputStream packages_file = new FileInputStream(FILE_PACKAGES_XLS);
        // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
        HSSFWorkbook packages_workbook = new HSSFWorkbook(packages_file);
        // Get first sheet from workbook
        HSSFSheet packages_sheet = packages_workbook.getSheetAt(0);
        */
        // Iterate through all rows of first sheet
        Iterator<Row> rowIterator = packages_sheet.iterator();

        int num_rows = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (num_rows > 5) {
                String swissmedic_no5 = ""; // SwissmedicNo5 registration number (5 digits)
                String sequence_name = "";
                String package_id = "";
                String swissmedic_no8 = ""; // SwissmedicNo8 = SwissmedicNo5 + Package id (8 digits)
                String heilmittel_code = "";
                String package_size = "";
                String package_unit = "";
                String swissmedic_cat = "";
                String application_area = "";
                String public_price = "";
                String exfactory_price = "";
                String therapeutic_index = "";
                String withdrawn_str = "";
                String speciality_str = "";
                String plimitation_str = "";
                String add_info_str = ""; // Contains additional information separated by ;
                String ean_code_str = "";
                String pharma_code_str = "";

                // 0: Zulassungsnummer, 1: Dosisstrkenummer, 2: Prparatebezeichnung, 3: Zulassunginhaberin, 4: Heilmittelcode, 5: IT-Nummer, 6: ATC-Code
                // 7: Erstzulassung Prparat, 8: Zulassungsdatum Sequenz, 9: Gltigkeitsdatum, 10: Packungscode, 11: Packungsgrsse
                // 12: Einheit, 13: Abgabekategorie Packung, 14: Abgabekategorie Dosisstrke, 15: Abgabekategorie Prparat, 
                // 16: Wirkstoff, 17: Zusammensetzung, 18: Anwendungsgebiet Prparat, 19: Anwendungsgebiet Dosisstrke, 20: Gentechnisch hergestellte Wirkstoffe
                // 21: Kategorie bei Insulinen, 22: Betubungsmittelhaltigen Prparaten

                // @cybermax: 15.10.2013 - work around for Excel cells of type "Special" (cell0 and cell10)
                if (row.getCell(0) != null)
                    swissmedic_no5 = String.format("%05d", (int) (row.getCell(0).getNumericCellValue())); // Swissmedic registration number (5 digits)
                if (row.getCell(2) != null)
                    sequence_name = ExcelOps.getCellValue(row.getCell(2)); // Sequence name
                if (row.getCell(4) != null)
                    heilmittel_code = ExcelOps.getCellValue(row.getCell(4)); // Heilmittelcode               
                if (row.getCell(11) != null)
                    package_size = ExcelOps.getCellValue(row.getCell(11)); // Packungsgrsse
                if (row.getCell(12) != null)
                    package_unit = ExcelOps.getCellValue(row.getCell(12)); // Einheit
                if (row.getCell(13) != null)
                    swissmedic_cat = ExcelOps.getCellValue(row.getCell(13)); // Abgabekategorie Packung   
                if (row.getCell(18) != null)
                    application_area = ExcelOps.getCellValue(row.getCell(18)); // Anwendungsgebiet Prparat            
                if (row.getCell(10) != null) {
                    package_id = String.format("%03d", (int) (row.getCell(10).getNumericCellValue())); // Verpackungs ID
                    swissmedic_no8 = swissmedic_no5 + package_id;
                    // Fill in row
                    ArrayList<String> pack = new ArrayList<String>();
                    pack.add(swissmedic_no5); // 0
                    pack.add(sequence_name); // 1
                    pack.add(heilmittel_code); // 2
                    pack.add(package_size); // 3
                    pack.add(package_unit); // 4
                    pack.add(swissmedic_cat); // 5
                    if (!application_area.isEmpty())
                        pack.add(application_area + " (Swissmedic);"); // 6 = swissmedic + bag
                    else
                        pack.add("");
                    pack.add(public_price); // 7
                    pack.add(exfactory_price); // 8
                    pack.add(therapeutic_index);// 9
                    // By default the meds are "ausser Handel"
                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                        withdrawn_str = "a.H."; // ausser Handel
                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                        withdrawn_str = "p.c."; // 
                    pack.add(withdrawn_str); // 10
                    pack.add(speciality_str); // 11
                    pack.add(plimitation_str); // 12
                    pack.add(add_info_str); // 13
                    // 22.03.2014: EAN-13 barcodes - initialization - check digit is missing!
                    ean_code_str = "7680" + swissmedic_no8;
                    pack.add(ean_code_str); // 14
                    pack.add(pharma_code_str); // 15

                    m_package_info.put(swissmedic_no8, pack);
                }
            }
            num_rows++;
        }
        long stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS) {
            System.out.println(
                    (m_package_info.size() + 1) + " packages in " + (stopTime - startTime) / 1000.0f + " sec");
        }
        startTime = System.currentTimeMillis();

        if (CmlOptions.SHOW_LOGS)
            System.out.print("- Processing atc classes xls... ");
        if (CmlOptions.DB_LANGUAGE.equals("de")) {
            /*
            // Load ATC classes xls file
            FileInputStream atc_classes_file = new FileInputStream(Constants.FILE_ATC_CLASSES_XLS);
            // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
            HSSFWorkbook atc_classes_workbook = new HSSFWorkbook(atc_classes_file);
            // Get first sheet from workbook
            // HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(1);   // --> 2013 file
            HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(0);      // --> 2014 file         
            // Iterate through all rows of first sheet
            rowIterator = atc_classes_sheet.iterator();
                    
            num_rows = 0;
            while (rowIterator.hasNext()) {
               Row row = rowIterator.next();
               if (num_rows>2) {
                  String atc_code = "";
                  String atc_class = "";
                  if (row.getCell(0)!=null) {
             atc_code = row.getCell(0).getStringCellValue().replaceAll("\\s", "");
                  }
                  if (row.getCell(2)!=null) {
             atc_class = row.getCell(2).getStringCellValue();
                  }
                  // Build a full map atc code to atc class
                  if (atc_code.length()>0) {
             m_atc_map.put(atc_code, atc_class);
                  }
               }
               num_rows++;
            }
            */
            CSVReader reader = new CSVReader(
                    new InputStreamReader(new FileInputStream(Constants.FILE_EPHA_ATC_CODES_CSV), "UTF-8"));
            List<String[]> myEntries = reader.readAll();
            num_rows = myEntries.size();
            for (String[] s : myEntries) {
                if (s.length > 2) {
                    String atc_code = s[0];
                    String atc_class = s[1];
                    m_atc_map.put(atc_code, atc_class);
                }
            }
            reader.close();
        } else if (CmlOptions.DB_LANGUAGE.equals("fr")) {
            // Load ATC classes xls file
            FileInputStream atc_classes_file = new FileInputStream(Constants.FILE_WHO_ATC_CLASSES_XLS);
            // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
            HSSFWorkbook atc_classes_workbook = new HSSFWorkbook(atc_classes_file);
            // Get first sheet from workbook
            HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(0); // --> 2014 file         
            // Iterate through all rows of first sheet
            rowIterator = atc_classes_sheet.iterator();

            num_rows = 0;
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (num_rows > 0) {
                    String atc_code = "";
                    String atc_class = "";
                    if (row.getCell(1) != null) {
                        atc_code = row.getCell(1).getStringCellValue();
                        if (atc_code.length() > 0) {
                            // Extract L5 and below
                            if (atc_code.length() < 6 && row.getCell(2) != null) {
                                atc_class = row.getCell(2).getStringCellValue();
                                // Build a full map atc code to atc class
                                m_atc_map.put(atc_code, atc_class);
                                // Extract L7
                            } else if (atc_code.length() == 7 && row.getCell(4) != null) {
                                atc_class = row.getCell(4).getStringCellValue();
                                m_atc_map.put(atc_code, atc_class);
                            }
                        }
                    }
                }
                num_rows++;
            }

            // Load multilingual ATC classes txt file, replace English with French
            String atc_classes_multi = FileOps.readFromFile(Constants.FILE_ATC_MULTI_LINGUAL_TXT);
            // Loop through all lines
            Scanner scanner = new Scanner(atc_classes_multi);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                List<String> atc_class = Arrays.asList(line.split(": "));
                String atc_code = atc_class.get(0);
                String[] atc_classes_str = atc_class.get(1).split(";");
                String atc_class_french = atc_classes_str[1].trim();
                // Replaces atc code...
                m_atc_map.put(atc_code, atc_class_french);
            }
            scanner.close();
        }
        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(
                    (m_atc_map.size() + 1) + " classes in " + (stopTime - startTime) / 1000.0f + " sec");

        // Load Refdata xml file
        File refdata_xml_file = new File(Constants.FILE_REFDATA_PHARMA_XML);
        FileInputStream refdata_fis = new FileInputStream(refdata_xml_file);

        startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println("- Unmarshalling Refdatabase for " + CmlOptions.DB_LANGUAGE + "... ");

        JAXBContext context = JAXBContext.newInstance(Refdata.class);
        Unmarshaller um = context.createUnmarshaller();
        Refdata refdataPharma = (Refdata) um.unmarshal(refdata_fis);
        List<Refdata.ITEM> pharma_list = refdataPharma.getItem();

        String smno8;
        for (Refdata.ITEM pharma : pharma_list) {
            String ean_code = pharma.getGtin();
            String pharma_code = pharma.getPhar();
            if (ean_code.length() == 13) {
                smno8 = ean_code.substring(4, 12);
                // Extract pharma corresponding to swissmedicno8 (source: swissmedic package file)
                ArrayList<String> pi_row = m_package_info.get(smno8);
                // Replace sequence_name
                if (pi_row != null) {
                    // Prparatname + galenische Form
                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                        pi_row.set(1, pharma.getNameDE());
                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                        pi_row.set(1, pharma.getNameFR());
                    // If med is in refdata file, then it is "in Handel!!" ;)
                    pi_row.set(10, ""); // By default this is set to a.H. or p.C.
                    // 22.03.2014: EAN-13 barcodes - replace with refdata if package exists
                    pi_row.set(14, ean_code);
                    // Pharma code
                    pi_row.set(15, pharma_code);
                } else {
                    if (CmlOptions.SHOW_ERRORS) {
                        if (pharma.getATYPE().equals("PHARMA"))
                            System.err.println(
                                    ">> Does not exist in BAG xls: " + smno8 + " (" + pharma.getNameDE() + ")");
                    }
                }
            } else if (ean_code.length() < 13) {
                if (CmlOptions.SHOW_ERRORS)
                    System.err.println(">> EAN code too short: " + ean_code + ": " + pharma.getNameDE());
            } else if (ean_code.length() > 13) {
                if (CmlOptions.SHOW_ERRORS)
                    System.err.println(">> EAN code too long: " + ean_code + ": " + pharma.getNameDE());
            }
        }

        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(pharma_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec");

        // Load BAG xml file
        File bag_xml_file = new File(Constants.FILE_PREPARATIONS_XML);
        FileInputStream fis_bag = new FileInputStream(bag_xml_file);

        startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println("- Processing preparations xml... ");

        context = JAXBContext.newInstance(Preparations.class);
        um = context.createUnmarshaller();
        Preparations prepInfos = (Preparations) um.unmarshal(fis_bag);
        List<Preparations.Preparation> prep_list = prepInfos.getPreparations();

        int num_preparations = 0;
        for (Preparations.Preparation prep : prep_list) {
            String swissmedicno5_str = prep.getSwissmedicNo5();
            if (swissmedicno5_str != null) {
                String orggencode_str = ""; // "O", "G" or empty -> ""
                String flagSB20_str = ""; // "Y" -> 20% or "N" -> 10%
                if (prep.getOrgGenCode() != null)
                    orggencode_str = prep.getOrgGenCode();
                if (prep.getFlagSB20() != null) {
                    flagSB20_str = prep.getFlagSB20();
                    if (flagSB20_str.equals("Y")) {
                        if (CmlOptions.DB_LANGUAGE.equals("de"))
                            flagSB20_str = "SB 20%";
                        else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                            flagSB20_str = "QP 20%";
                    } else if (flagSB20_str.equals("N")) {
                        if (CmlOptions.DB_LANGUAGE.equals("de"))
                            flagSB20_str = "SB 10%";
                        else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                            flagSB20_str = "QP 10%";
                    } else
                        flagSB20_str = "";
                }
                m_add_info_map.put(swissmedicno5_str, orggencode_str + ";" + flagSB20_str);
            }

            List<Preparation.Packs> packs_list = prep.getPacks();
            for (Preparation.Packs packs : packs_list) {
                // Extract codes for therapeutic index / classification
                String bag_application = "";
                String therapeutic_code = "";
                List<Preparations.Preparation.ItCodes> itcode_list = prep.getItCodes();
                for (Preparations.Preparation.ItCodes itc : itcode_list) {
                    List<Preparations.Preparation.ItCodes.ItCode> code_list = itc.getItCode();
                    int index = 0;
                    for (Preparations.Preparation.ItCodes.ItCode code : code_list) {
                        if (index == 0) {
                            if (CmlOptions.DB_LANGUAGE.equals("de"))
                                therapeutic_code = code.getDescriptionDe();
                            else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                therapeutic_code = code.getDescriptionFr();
                        } else {
                            if (CmlOptions.DB_LANGUAGE.equals("de"))
                                bag_application = code.getDescriptionDe();
                            else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                bag_application = code.getDescriptionFr();
                        }
                        index++;
                    }
                }
                // Generate new package info
                List<Preparation.Packs.Pack> pack_list = packs.getPack();
                for (Preparation.Packs.Pack pack : pack_list) {
                    // Get SwissmedicNo8 and used it as a key to extract all the relevant package info
                    String swissMedicNo8 = pack.getSwissmedicNo8();
                    ArrayList<String> pi_row = null;
                    if (swissMedicNo8 != null)
                        pi_row = m_package_info.get(swissMedicNo8);
                    // Preparation also in BAG xml file (we have a price)
                    if (pi_row != null) {
                        // Update Swissmedic catory if necessary ("N->A", Y->"A+")
                        if (pack.getFlagNarcosis().equals("Y"))
                            pi_row.set(5, pi_row.get(5) + "+");
                        // Extract point limitations
                        List<Preparations.Preparation.Packs.Pack.PointLimitations> point_limits = pack
                                .getPointLimitations();
                        for (Preparations.Preparation.Packs.Pack.PointLimitations limits : point_limits) {
                            List<Preparations.Preparation.Packs.Pack.PointLimitations.PointLimitation> plimits_list = limits
                                    .getPointLimitation();
                            if (plimits_list.size() > 0)
                                if (plimits_list.get(0) != null)
                                    pi_row.set(12, ", LIM" + plimits_list.get(0).getPoints() + "");
                        }
                        // Extract exfactory and public prices
                        List<Preparations.Preparation.Packs.Pack.Prices> price_list = pack.getPrices();
                        for (Preparations.Preparation.Packs.Pack.Prices price : price_list) {
                            List<Preparations.Preparation.Packs.Pack.Prices.PublicPrice> public_price = price
                                    .getPublicPrice();
                            List<Preparations.Preparation.Packs.Pack.Prices.ExFactoryPrice> exfactory_price = price
                                    .getExFactoryPrice();
                            if (exfactory_price.size() > 0) {
                                try {
                                    float f = Float.valueOf(exfactory_price.get(0).getPrice());
                                    String ep = String.format("%.2f", f);
                                    pi_row.set(8, "CHF " + ep);
                                } catch (NumberFormatException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Number format exception (exfactory price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                }
                            }
                            if (public_price.size() > 0) {
                                try {
                                    float f = Float.valueOf(public_price.get(0).getPrice());
                                    String pp = String.format("%.2f", f);
                                    pi_row.set(7, "CHF " + pp);
                                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                                        pi_row.set(11, ", SL");
                                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                        pi_row.set(11, ", LS");
                                } catch (NullPointerException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Null pointer exception (public price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                } catch (NumberFormatException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Number format exception (public price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                }
                            }
                            // Add application area and therapeutic code
                            if (!bag_application.isEmpty())
                                pi_row.set(6, pi_row.get(6) + bag_application + " (BAG)");
                            pi_row.set(9, therapeutic_code);
                        }
                    }
                }
            }
            num_preparations++;
        }

        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(
                    num_preparations + " preparations in " + (stopTime - startTime) / 1000.0f + " sec");

        // Loop through all SwissmedicNo8 numbers
        /*
        for (Map.Entry<String, ArrayList<String>> entry : package_info.entrySet()) {
           String swissmedicno8 = entry.getKey();
           ArrayList<String> pi_row = entry.getValue();
        }
        */

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

From source file:com.quinsoft.zeidon.utils.PortableFileReader.java

public void readEntities() {
    boolean closeReader = false;
    if (reader == null) {
        reader = new BufferedBinaryStreamReader(inputStream);
        closeReader = true;/*from  w w  w . j  av a2  s  .  c  o m*/
    }

    lineNumber = 0;
    try {
        ArrayList<PortableFileAttributeHandler> attributeHandlerStack = new ArrayList<PortableFileAttributeHandler>();

        int currentLevel = 0;
        String currentEntityName = null;

        // If we are reading multiple OIs in a single stream we expect to find 'ZEND'
        // to indicate one OI has ended and the next one begins.  Set endOfCurrentOi
        // to true so we can exit activating the current OI.
        boolean endOfCurrentOi = false;

        while (!endOfCurrentOi && (line = reader.readLine()) != null) {
            lineNumber++;

            if (StringUtils.isBlank(line))
                continue;

            String values[] = splitLine(line, ' ');
            attributeName = values[0];
            attributeValue = values[1];

            switch (attributeName.charAt(0)) {
            case 'e':
                attributeName = attributeName.substring(1);
                values = splitLine(attributeValue, ',');
                int level = Integer.parseInt(values[0]);

                if (currentLevel > 0)
                    entityHandler.endEntityAttributes(this, currentEntityName, currentLevel);

                if (values[1] != EMPTY_STRING)
                    entityFlags = Long.parseLong(values[1]);

                currentEntityName = attributeName;

                while (currentLevel >= level) {
                    attributeHandler = attributeHandlerStack.get(currentLevel);
                    entityHandler.endEntity(this, attributeHandler, currentLevel);
                    currentLevel--;
                }

                attributeHandler = entityHandler.createEntity(this, level, entityFlags);

                if (level >= attributeHandlerStack.size())
                    attributeHandlerStack.add(attributeHandler);
                else
                    attributeHandlerStack.set(level, attributeHandler);

                currentLevel = level;
                break;

            case 'a':
                if (incremental || attribFlags) {
                    values = splitLine(attributeName, ',');
                    if (values[1] != EMPTY_STRING) {
                        attributeName = values[0];
                        attributeFlags = Long.parseLong(values[1]);
                    }
                } else
                    attributeFlags = 0;

                attributeName = attributeName.substring(1);
                if (attributeHandler != null) {
                    try {
                        if (attributeValue.length() > 0 && attributeValue.charAt(0) == STRING_STORED_AS_BLOB) {
                            attributeValue = attributeValue.substring(1); // Skip past control char.
                            int length = Integer.parseInt(attributeValue);
                            attributeValueBytes = new byte[length];
                            try {
                                int read = reader.read(attributeValueBytes, length);
                                assert read == length;
                                attributeValue = new String(attributeValueBytes);
                            } catch (IOException e) {
                                throw new ZeidonException("Error reading binary data from portable file");
                            }

                            lineNumber += StringUtils.countMatches(attributeValue, "\n") + 1;
                        }
                        attributeHandler.setAttribute(this);
                    } catch (Throwable e) {
                        throw ZeidonException.prependMessage(e, "Attribute Name '%s'", attributeName);
                    }
                }

                break;

            case 'i':
                int target = Integer.parseInt(attributeName.substring(1));
                int source = Integer.parseInt(attributeValue);

                entityHandler.link(this, target, source);
                break;

            case 'Z':
                if (!"ZEND".equals(line))
                    throw new ZeidonException("Expecting 'ZEND' but got %s instead", line);

                // Set flag to break out of reader loop.
                endOfCurrentOi = true;
                break;

            case 'z':
                boolean erDate;
                attributeHandlerStack.add(null);

                if (lineNumber > 2)
                    throw new ZeidonException("Unexpected beginning of new OI in stream on line %d",
                            lineNumber);

                // Read the flags from the header.  Sample header:
                // z1100-Zeidon    MEMPLOY  mEmploy  07/12/09   20:38:04 1.0a2
                erDate = line.charAt(1) == '1';
                incremental = line.charAt(2) == '1';
                compressed = line.charAt(3) == '1';
                optimisticOIs = line.charAt(4) == '1';
                attribFlags = line.charAt(5) == '1';
                if (compressed)
                    throw new ZeidonException("Reading compressed streams not supported yet.");

                String lodDefName = StringUtils.split(line.substring(24), " ", 3)[0];
                entityHandler.startFile(this, lodDefName);

                if (erDate && isIncremental()) {
                    // File contains the ER date so read it.  We don't support compressed
                    // OIs yet so we don't do anything with it.
                    reader.readLine();
                }

                break;

            case ';':
                // Comment line, so just ignore.
                break;

            case 'm':
                //TODO: Add support for meta flags.
                break;

            default:
                throw new ZeidonException("Line %d doesn't start with e, a, i, or z\n==> %s", lineNumber, line);
            }
        } // while not EOF...

        if (currentLevel > 0)
            entityHandler.endEntityAttributes(this, currentEntityName, currentLevel);

        while (currentLevel > 0) {
            attributeHandler = attributeHandlerStack.get(currentLevel);
            entityHandler.endEntity(this, attributeHandler, currentLevel);
            currentLevel--;
        }

        entityHandler.endFile();
    } catch (Throwable e) {
        // Add line number to the message.
        throw ZeidonException.prependMessage(e, "line:%d", lineNumber);
    } finally {
        if (closeReader) {
            IOUtils.closeQuietly(reader);
            reader = null;
        }
    }
}