Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

In this page you can find the example usage for java.lang Exception getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:org.alfresco.reporting.processor.NodeRefBasedPropertyProcessor.java

@Override
protected ReportLine processNodeToMap(String identifier, String table, ReportLine rl) {
    table = dbhb.fixTableColumnName(table);
    if (logger.isDebugEnabled())
        logger.debug("processNodeToMap, identifier=" + identifier);

    NodeRef masterRef = null;/*from  w  w w .j av a2 s . c o m*/
    NodeRef nodeRef = new NodeRef(identifier.split(",")[0]);
    if (identifier.contains(",")) {
        masterRef = new NodeRef(identifier.split(",")[1]);
    }

    // NodeRef nodeRef=new NodeRef(identifier);
    if (logger.isDebugEnabled())
        logger.debug("Enter processNodeToMap nodeRef=" + nodeRef);
    try {
        // logger.debug("processNodeToMap: processing values");
        rl = processPropertyValues(rl, nodeRef);
    } catch (Exception e) {
        // logger.error("processprocessNodeToMap: That is weird,
        // processPropertyValues crashed! " + nodeRef);
        e.printStackTrace();
    }

    try {
        rl = processAssociationValues(rl, nodeRef);
    } catch (Exception e) {
        // logger.error("processNodeToMap: That is weird,
        // processAssociationValues crashed! " + nodeRef);
        e.printStackTrace();
    }

    try {
        rl.setLine(Constants.COLUMN_NODEREF, getClassToColumnType().getProperty("noderef"), nodeRef.toString(),
                getReplacementDataType());
    } catch (Exception e) {
        // logger.error("processNodeToMap: That is weird,
        // rl.setLine(noderef) crashed! " + nodeRef);
        e.printStackTrace();
    }

    try {
        String typeString = nodeService.getType(nodeRef).getLocalName(); // .getPrefixedQName(resolver);//
        // apparently for native documents (cm:content) the type == null.
        // Code below should fix
        if (typeString == null) {
            typeString = nodeService.getType(nodeRef).toString();
            typeString = typeString.substring(typeString.lastIndexOf(":"));
        }
        rl.setLine(Constants.COLUMN_OBJECT_TYPE,
                getClassToColumnType().getProperty(Constants.COLUMN_OBJECT_TYPE, ""), typeString,
                getReplacementDataType());
    } catch (Exception e) {
        // it does not have a type (??). Bad luck. Don't crash
        // (versionStore?!)
        logger.debug("EXCPTION1: // it does not have a Type. Bad luck. Don't crash (versionStore?!)");
        e.printStackTrace();

    }

    String aspectString = "";
    try {
        Set<QName> aspectsSet = nodeService.getAspects(nodeRef);
        Iterator<QName> aspectIterator = aspectsSet.iterator();
        while (aspectIterator.hasNext()) {
            QName aspect = aspectIterator.next();
            if (aspectString.length() > 0) {
                aspectString += ",";
            }

            aspectString += aspect.getLocalName(); // getPrefixedQName(resolver);//
            // getLocalName();
        } // end while

        rl.setLine(Constants.COLUMN_ASPECTS, getClassToColumnType().getProperty(Constants.COLUMN_ASPECTS, ""),
                aspectString, getReplacementDataType());
    } catch (Exception e) {
        // it does not have aspects. Bad luck. Don't crash (versionStore?!)
        // logger.debug("EXCPTION1: // it does not have Aspects. Bad luck.
        // Don't crash (versionStore?!)");
        e.printStackTrace();

    }

    Path path;
    String displayPath = "";
    try {
        path = getNodeService().getPath(nodeRef);
        displayPath = toDisplayPath(path);
        rl.setLine(Constants.COLUMN_PATH, getClassToColumnType().getProperty(Constants.COLUMN_PATH),
                displayPath, getReplacementDataType());
    } catch (Exception e) {
        // it does not have a path. Bad luck. Don't crash (versionStore?!)
        // logger.debug("EXCPTION1: // it is not in a site. Bad luck. Don't
        // crash (versionStore?!)");
        e.printStackTrace();
    }

    String site = "";
    try {
        site = getSiteName(nodeRef);
        rl.setLine(Constants.COLUMN_SITE, getClassToColumnType().getProperty(Constants.COLUMN_SITE), site,
                getReplacementDataType());
    } catch (Exception e) {
        // it is not in a site. Bad luck. Don't crash
    }
    QName myType = getNodeService().getType(nodeRef);

    if (getDictionaryService().isSubClass(myType, ContentModel.TYPE_FOLDER)) {
        NodeRef origNodeRef = null;
        try {
            if (nodeRef.toString().startsWith(StoreRef.PROTOCOL_ARCHIVE)) {
                ChildAssociationRef car = (ChildAssociationRef) nodeService.getProperty(nodeRef,
                        QName.createQName("http://www.alfresco.org/model/system/1.0",
                                "archivedOriginalParentAssoc"));

                logger.debug("ORIGIN: child:" + car.getChildRef() + " parent: " + car.getParentRef());
                origNodeRef = car.getChildRef();

            }
        } catch (Exception e) {
            logger.fatal("Exception getting orig_noderef" + e.getStackTrace());
        }

        if (origNodeRef != null) {
            // it is an archived thingy
            if (logger.isDebugEnabled())
                logger.debug("Setting Ref from archive to orig_noderef!!!");

            rl.setLine(Constants.COLUMN_ORIG_NODEREF, getClassToColumnType().getProperty("noderef"),
                    origNodeRef.toString(), getReplacementDataType());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Setting currentRef to orig_noderef!!!");

            rl.setLine(Constants.COLUMN_ORIG_NODEREF, getClassToColumnType().getProperty("noderef"),
                    nodeRef.toString(), getReplacementDataType());
        }
    }

    if (getDictionaryService().isSubClass(myType, ContentModel.TYPE_CONTENT)
            || (getDictionaryService().getType(myType)).toString()
                    .equalsIgnoreCase(ContentModel.TYPE_CONTENT.toString())) {
        long size = 0;
        String sizeString = "0";
        try {
            size = getFileFolderService().getFileInfo(nodeRef).getContentData().getSize();

            if (size == 0) {
                sizeString = "0";
            } else {
                sizeString = Long.toString(size);
            }
            // get the COLUMN_SIZE prop, being "size" for MySQL, but
            // "docsize" for Oracle
            rl.setLine(COLUMN_SIZE, getClassToColumnType().getProperty(COLUMN_SIZE), sizeString,
                    getReplacementDataType());
        } catch (Exception e) {
            logger.info("processNodeToMap: Huh, no size?");
            sizeString = "0";
        }

        boolean versioned = false;

        try {
            versioned = getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
            rl.setLine("versioned", getClassToColumnType().getProperty("boolean"), String.valueOf(versioned),
                    getReplacementDataType());
        } catch (Exception e) {
            logger.info("processNodeToMap: Huh, no versioned info?");
            e.printStackTrace();
        }

        try {
            String mimetype = getFileFolderService().getFileInfo(nodeRef).getContentData().getMimetype();
            if (mimetype == null)
                mimetype = "NULL";
            rl.setLine(Constants.COLUMN_MIMETYPE, getClassToColumnType().getProperty(Constants.COLUMN_MIMETYPE),
                    mimetype, getReplacementDataType());
        } catch (Exception e) {
            logger.info("processNodeToMap: Huh, no mimetype?");
        }

        NodeRef origNodeRef = null;
        try {
            if (nodeRef.toString().startsWith(StoreRef.PROTOCOL_ARCHIVE)) {
                ChildAssociationRef car = (ChildAssociationRef) nodeService.getProperty(nodeRef,
                        QName.createQName("http://www.alfresco.org/model/system/1.0",
                                "archivedOriginalParentAssoc"));

                logger.debug("ORIGIN: child:" + car.getChildRef() + " parent: " + car.getParentRef());
                origNodeRef = car.getChildRef();

            }
        } catch (Exception e) {
            logger.warn("Exception getting orig_noderef" + e.getStackTrace());
        }

        try {
            if (nodeRef.toString().startsWith("version")) {
                // replace all archive-space references in the orig_noderef
                // into the workspace one.
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting nodeRef to orig_noderef - VERSION!!!");
                    logger.debug("Master says: " + masterRef.toString());
                }

                rl.setLine(Constants.COLUMN_ORIG_NODEREF, getClassToColumnType().getProperty("noderef"),
                        masterRef.toString(), getReplacementDataType());
            } else {
                if (origNodeRef != null) {
                    // it is an archived thingy
                    if (logger.isDebugEnabled())
                        logger.debug("Setting Ref from archive to orig_noderef!!!");

                    rl.setLine(Constants.COLUMN_ORIG_NODEREF, getClassToColumnType().getProperty("noderef"),
                            origNodeRef.toString(), getReplacementDataType());
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Setting currentRef to orig_noderef!!!");

                    rl.setLine(Constants.COLUMN_ORIG_NODEREF, getClassToColumnType().getProperty("noderef"),
                            nodeRef.toString(), getReplacementDataType());
                }

            }
        } catch (Exception e) {
            // don't crash... (versionStore?!)
            // logger.debug("EXCPTION: don't crash... (versionStore?!)");
        }
    } // end if
    else {
        if (logger.isDebugEnabled())
            logger.debug(myType.toString() + " is no content subclass!");
    }
    return rl;
}

From source file:ru.apertum.qsystem.client.forms.FAdmin.java

@Action
    public void saveConfiguration() {
        saveNet();/*ww  w.jav  a 2s .  c o  m*/
        final Exception res;
        try {
            res = (Exception) Spring.getInstance().getTt().execute(new TransactionCallback() {

                @Override
                public Exception doInTransaction(TransactionStatus status) {
                    try {
                        //? ? ?
                        Spring.getInstance().getHt().saveOrUpdate(ServerProps.getInstance().getProps());
                        //?  
                        Spring.getInstance().getHt().saveOrUpdate(ServerProps.getInstance().getStandards());

                        // ?  ???
                        QScheduleList.getInstance().save();
                        // ?   ??
                        QBreaksList.getInstance().save();
                        // ?  ?
                        QCalendarList.getInstance().save();
                        // ? ?
                        QServiceTree.getInstance().save();
                        // ? 
                        QUserList.getInstance().save();
                        // ? 
                        QInfoTree.getInstance().save();
                        // ? 
                        QResponseList.getInstance().save();
                        // ?   ? ? 
                        QResultList.getInstance().save();
                        QLog.l().logger().debug(" .");
                    } catch (Exception ex) {
                        QLog.l().logger().error("  ? \n" + ex.toString() + "\n"
                                + Arrays.toString(ex.getStackTrace()));
                        status.setRollbackOnly();
                        return ex;
                    }
                    return null;
                }
            });
        } catch (RuntimeException ex) {
            throw new ClientException(
                    " ?  ?   (JDBC).        ?.\n("
                            + ex.toString() + ")");
        }
        if (res == null) {
            JOptionPane.showMessageDialog(this, getLocaleMessage("admin.save.title"),
                    getLocaleMessage("admin.save.caption"), JOptionPane.INFORMATION_MESSAGE);
        } else {
            throw new ClientException(
                    " ?  ?   (JDBC).        ?.\n["
                            + res.getLocalizedMessage() + "]\n(" + res.toString() + ")\nSQL: ");
        }
    }

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.RefactorOperationController.java

private String doFixDataTypes(HttpServletRequest request, HttpServletResponse response) {
    try {//from  w w w.  j a va2s . com
        super.doGet(request, response);
    } catch (Exception e) {
        log.error(this.getClass().getName() + " caught exception calling doGet()");
    }
    VitroRequest vreq = new VitroRequest(request);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", Controllers.CHECK_DATATYPE_PROPERTIES);
    request.setAttribute("title", "Check Datatype Properties");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");

    OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel(FULL_ASSERTIONS);
    ontModel.enterCriticalSection(Lock.WRITE);
    ArrayList<String> results = new ArrayList<String>();

    try {
        ExtendedIterator dataProperties = ontModel.listDatatypeProperties();
        int hasRange = 0;
        int consistent = 0;
        int inconsistent = 0;
        int total = 0;
        int fixed = 0;
        while (dataProperties.hasNext()) // Iterate through all datatype properties
        {
            total++;
            DatatypeProperty p = (DatatypeProperty) dataProperties.next();
            OntResource range = p.getRange();
            if (range != null)
                hasRange++;
            NodeIterator n = ontModel.listObjectsOfProperty(p);
            //if(!n.hasNext()) results.add(p.getLocalName()+" is not in any statements");
            while (n.hasNext()) // Iterate through all objects of all datatype properties
            {
                RDFNode node = n.nextNode();
                if (node.isLiteral()) {
                    if (range != null) // If a literal has a predicate with a defined range, check and fix the literal's datatype
                    {
                        Literal l = (Literal) node;
                        StmtIterator usingPandL = ontModel.listStatements(null, p, l);
                        int size = 0;
                        results.add("Statements using property " + p.getLocalName() + " and literal "
                                + l.getLexicalForm() + ":");
                        while (usingPandL.hasNext()) {
                            Statement st = usingPandL.nextStatement();
                            results.add("    " + st.getSubject().getLocalName() + " " + p.getLocalName() + " "
                                    + l.getLexicalForm());
                            size++;
                        }
                        usingPandL.close();
                        boolean valid = range.getURI().equals(l.getDatatypeURI());
                        if (valid)
                            consistent += size;
                        else {
                            results.add(p.getLocalName() + " has object " + l.getLexicalForm() + " of type "
                                    + l.getDatatypeURI() + " which is inconsistent");
                            String typeName = "";
                            if (range.getURI().contains(XSDDatatype.XSD))
                                typeName = range.getURI().substring(XSDDatatype.XSD.length() + 1);
                            else
                                results.add("ERROR: " + p.getLocalName()
                                        + " has a range which does not contain the XSD namespace");
                            Literal newLiteral = null;
                            try {
                                newLiteral = ontModel.createTypedLiteral(l.getLexicalForm(),
                                        new XSDDatatype(typeName));
                            } catch (NullPointerException e) {
                                results.add(
                                        "ERROR: Can't create XSDDatatype for literal " + l.getLexicalForm());
                            }
                            StmtIterator badStatements = ontModel.listStatements(null, p, l);
                            StmtIterator toRemove = ontModel.listStatements(null, p, l);
                            ArrayList<Statement> queue = new ArrayList<Statement>();
                            while (badStatements.hasNext()) {
                                Statement badState = badStatements.nextStatement();
                                Statement goodState = ontModel.createStatement(badState.getSubject(), p,
                                        newLiteral);
                                queue.add(goodState);
                                results.add("    Replacing: " + badState.toString());
                                results.add("    With:      " + goodState.toString());
                                fixed++;
                            }
                            for (int i = 0; i < queue.size(); i++) {
                                ontModel.add(queue.get(i));
                            }
                            ontModel.remove(toRemove);
                            badStatements.close();
                            toRemove.close();
                        }
                        if (valid)
                            results.add("Literal " + l.getLexicalForm() + " is in the range of property "
                                    + p.getLocalName());
                        results.add("--------------");
                    }
                } else
                    results.add("ERROR: " + node.toString() + " is not a literal");

            }
            n.close();
        }
        dataProperties.close();

        results.add(hasRange + " of " + total + " datatype properties have defined ranges.");
        results.add("Of the statements that contain datatype properties with defined ranges, " + consistent
                + " are consistent and " + fixed + " are inconsistent.");
        results.add(fixed + " statements have been fixed.");
        //for(int i=0; i<results.size(); i++) System.out.println(results.get(i));

    } finally {
        ontModel.leaveCriticalSection();
    }
    request.setAttribute("results", results);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error(this.getClass().getName() + " could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

    return "";
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * Processes requests from the client for both HTTP <code>GET</code>
 * and <code>POST</code> methods.
 *
 * @param request servlet request/*from  w  w w. j a  v  a 2  s  .  c  om*/
 * @param response servlet response
 */
protected void processRequest(String requestType, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String responseFormat = response_format_prop;
    // flags that the user has not set the response format
    boolean defaultResponseFormat = response_format_prop.equals("XML") ? true : false;
    ServiceOperationInterface service = null;
    String callbackFunction = null;

    log.info(">> Start processRequest(" + requestType + ") at " + new Date());

    try {
        ServletContext context = getServletContext();

        String scriptName = request.getParameter(PARAM_SCRIPTNAME1); // look for "service=xxxx"
        String contextPath = "";

        /* If the service parameter is not specified then use the URL to get the service name... */

        if (scriptName == null) {
            scriptName = request.getPathInfo();
            contextPath = request.getContextPath();

            /*
            //Put this in for debugging...
            System.out.println("****** -> pathInfo       [" + request.getPathInfo() + "]");
            System.out.println("****** -> pathTranslated [" + request.getPathTranslated() + "]");
            System.out.println("****** -> contextPath    [" + request.getContextPath() + "]");
            System.out.println("****** -> localAddr      [" + request.getLocalAddr() + "]");
            System.out.println("****** -> localName      [" + request.getLocalName() + "]");
            System.out.println("****** -> requestURI     [" + request.getRequestURI() + "]");//*****
            System.out.println("****** -> servletPath    [" + request.getServletPath() + "]");
            */

            if (scriptName == null) {
                scriptName = "UNSPECIFIED_SERVICE";
            }
        }

        /* See if the URI is mapped to another service... */
        ServiceMapping serviceMapping;
        serviceMapping = serviceMapper.getURIMapping(""/*contextPath*/, scriptName, requestType);

        if (serviceMapping != null) {
            log.info("Redirect URI to [" + serviceMapping.getServiceName() + "]");

            scriptName = serviceMapping.getServiceName();

            /* If the URI has been mapped then see if the "Accept" header specifies the return type required... */
            String accept = request.getHeader("Accept");

            if (accept.indexOf("text/xml") != -1) {
                responseFormat = "XML";
                defaultResponseFormat = false;
            }
            if (accept.indexOf("text/json") != -1) {
                responseFormat = "JSON";
                defaultResponseFormat = false;
            }

        }

        if (scriptName.startsWith("/")) {
            scriptName = scriptName.substring(1, scriptName.length());
        }

        /**
         * If "log" service invoked then process it...
         */
        if (scriptName.equals("log")) {
            returnHTMLLog(response);
            return;
        }

        /**
         * If "health" service invoked then process it...
         */
        if (scriptName.equals("health")) {
            returnHealth(response);
            return;
        }

        /* Check for the flag to return XML or JSON objects... */

        if (request.getParameter(PARAM_RETURNXML) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "XML";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNJSON) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "JSON";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNRAW) != null) {
            println(">> Servlet will return raw text object.");
            responseFormat = "RAW";
            defaultResponseFormat = false;
        }

        /* Check for the callback function parameter... */

        callbackFunction = request.getParameter(PARAM_CALLBACK);

        /**
         * Check to see if the client wants a "Service Mapping Description" (SMD) for the 'service'...
         */

        if (request.getParameter(PARAM_SMD) != null) {

            log.info("Client wants SMD for [" + scriptName + "]");

            try {
                ServicePool pool = null;
                Map availableServices = null;
                ServiceMappingDescription smd = null;
                ServiceScriptPool serviceScriptPool = null;
                String serviceScriptName = null;
                String returnString = null;

                pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);
                availableServices = pool.getAvailableServices();
                smd = new ServiceMappingDescription(request.getRequestURL().toString(),
                        request.getRequestURL().toString() + "?smd", null);

                for (Iterator it = availableServices.values().iterator(); it.hasNext();) {

                    serviceScriptPool = (ServiceScriptPool) it.next();

                    serviceScriptName = serviceScriptPool.getPoolName();

                    /**
                     * If the service script name begins with the passed in script name then add it to the
                     * service mapping description...
                     */

                    log.debug("scriptName = [" + scriptName + "], serviceScriptName = [" + serviceScriptName
                            + "]");

                    if (scriptName.equals("") || serviceScriptName.startsWith(scriptName + "/")
                            || serviceScriptName.equals(scriptName)) {

                        smd.addOperation(serviceScriptName);

                        service = serviceScriptPool.getService();

                        smd.setOperationDescription(service.getScriptDescription());
                        smd.setOperationTransport(service.getHTTPMethods());
                        smd.setOperationEnvelope("URL");
                        smd.setOperationContentType(service.getResponseFormat());
                        smd.setOperationParameters(serviceScriptPool.getServiceParameters());
                        smd.setOperationReturns(serviceScriptPool.getServiceReturns());

                    }

                }

                returnString = smd.getSMDJSONString();

                writeResponse(returnString, "JSONRAW", callbackFunction, response);

            } catch (Exception ex) {
                log.error("Exception getting SMD: " + ex.toString());
                ex.printStackTrace();
            }

            return;
        }

        /**
         * Get the service and run it...
         */

        println(">> Client wants to invoke the service [" + scriptName + "]");

        try {
            service = getServiceScript(scriptName);
        } catch (Exception ex) {
            errorResponse(response,
                    "Could not get an instance of the service [" + scriptName + "]: " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        if (service == null) {
            errorResponse(response, "Service [" + scriptName + "] not found.", responseFormat,
                    callbackFunction);
            return;
        }

        /**
         * If the script exists in the toaster pool then invoke it
         */

        println(">> Checking login required");

        try {
            if (service.getLoginRequired().equals("true")) {

                HttpSession session = request.getSession(false);
                Object loggedIn = null;

                if (session != null) {
                    loggedIn = session.getAttribute(ATTRIB_LOGGED_IN);
                }

                log.trace("**** SESSION   = " + session);
                log.trace("**** Logged In = " + loggedIn);

                if (session == null || loggedIn == null || loggedIn.equals("true") == false) {
                    errorResponse(response,
                            "The service " + scriptName + " requires you to be logged in to run it.",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

                /* Check that the logged in user is authorised to run the service... */

                String validUsers;
                String[] validUsersArray;
                String user;
                String loggedInUser;
                boolean validUser;

                validUsers = service.getValidUsers();
                validUsersArray = validUsers.split("[,]");

                loggedInUser = (String) session.getAttribute(ATTRIB_LOGGED_IN_USER);

                validUser = false;

                for (int idx = 0; idx < validUsersArray.length; idx++) {
                    user = validUsersArray[idx].trim();
                    if (user.equals("*")) {
                        validUser = true;
                        break;
                    }
                    if (user.equals(loggedInUser)) {
                        validUser = true;
                        break;
                    }
                }

                if (validUser == false) {
                    log.error("The user [" + loggedInUser + "] is not authorised to invoke the service ["
                            + scriptName + "]");
                    errorResponse(response, "You are not authorised to invoke the service [" + scriptName + "]",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

            }
        } catch (Exception ex) {
            errorResponse(response, "Could not check if login required for this service. " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        boolean scriptInputSet = false;

        /*
         * Go through the set of parameters passed to us and set them up in the service instance...
         */
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();

            if (parameterName.equals(PARAM_SCRIPTNAME1) == true
                    || parameterName.equals(PARAM_SCRIPTNAME2) == true
                    || parameterName.equals(PARAM_RETURNXML) == true
                    || parameterName.equals(PARAM_RETURNJSON) == true
                    || parameterName.equals(PARAM_CALLBACK) == true) {
                continue;
            }

            String parameterValue = (String) request.getParameter(parameterName);

            if (parameterName.equals(PARAM_INPUTXML) == true) {
                service.setInputXML(parameterValue);
                scriptInputSet = true;
                continue;
            }

            if (parameterName.equals(PARAM_INPUTJSON) == true) {

                try {
                    // The input object is a JSON object... so convert it into XML...
                    JSONObject json = new JSONObject(parameterValue);

                    service.setInputXML(XML.toString(json));
                    scriptInputSet = true;
                    println("JSON converted to \n" + XML.toString(json));
                } catch (JSONException ex) {
                    errorResponse(response,
                            "Could not create JSON object." + ex.toString() + ". " + ex.getStackTrace(),
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }
                continue;
            }

            /* Any leftover parameters are query parameters. */
            println("Query Parameter found... Setting " + parameterName + " to " + parameterValue);
            service.setParameter(parameterName, parameterValue);

        } // End of parameters for loop

        /* If there is content in the request then, unless we have already set it, this is the input to the script... */

        if (requestType.equals("POST") && scriptInputSet == false) {

            try {
                BufferedReader reader = request.getReader();
                StringBuffer buf = new StringBuffer();
                String line;
                String postData;

                while ((line = reader.readLine()) != null) {
                    buf.append(line);
                }

                postData = buf.toString();

                log.debug("POST DATA: " + postData);

                if (postData.startsWith("<")) {
                    service.setInputXML(postData);
                    scriptInputSet = true;
                } else {
                    try {
                        // The input object is a JSON object... so convert it into XML...
                        JSONObject json = new JSONObject(postData);

                        service.setInputXML(XML.toString(json));
                        scriptInputSet = true;
                        log.debug("POST JSON converted to \n" + XML.toString(json));
                    } catch (JSONException ex) {
                        errorResponse(response, "Could not convert POSTed JSON object." + ex.toString() + ". "
                                + ex.getStackTrace(), responseFormat, callbackFunction);
                        freeServiceScript(service);
                        return;
                    }
                }

            } catch (Exception ex) {
                log.warn("Exception getting posted data: " + ex.toString());
                errorResponse(response, "Could not convert posted data.", responseFormat, callbackFunction);
                freeServiceScript(service);
                return;
            }

        }

        /* If the service name has been redirected then set any parameters that where embedded in the URI... */
        if (serviceMapping != null) {
            Properties serviceParameters = serviceMapping.getParameters();
            String paramName;
            String paramValue;
            for (Enumeration<Object> en = serviceParameters.keys(); en.hasMoreElements();) {
                paramName = (String) en.nextElement();
                paramValue = (String) serviceParameters.get(paramName);
                service.setParameter(paramName, paramValue);
            }
        }

        String serviceResultString = null;

        /**
         * Run the service script...
         */

        service.setSessionRequest(request);
        service.setSessionResponse(response);
        service.setCallbackFunction(callbackFunction);

        /* Check if the service has a predefined output format... */
        /* If the user has specified a format then that is used.. */

        String operationResponseFormat;

        operationResponseFormat = service.getResponseFormat();

        if (defaultResponseFormat == true && operationResponseFormat != null
                && operationResponseFormat.equals("") == false) {
            responseFormat = operationResponseFormat;
        }

        service.setInvokeResponseFormat(responseFormat);

        /* If this is a priviledged operation then pass in a reference to the servlet... */

        String priviledgedOperation = service.getPriviledged();

        if (priviledgedOperation.compareToIgnoreCase("true") == 0
                || priviledgedOperation.compareToIgnoreCase("yes") == 0
                || priviledgedOperation.compareToIgnoreCase("y") == 0) {

            service.setPriviledgedHelper(this);
        }

        serviceResultString = service.invokeOperation();

        if (serviceResultString == null) {
            errorResponse(response,
                    "Error invoking the operation.<br><b>" + service.getScriptMessage() + "</b>",
                    responseFormat, callbackFunction);
            freeServiceScript(service);
            return;
        }

        /* Return the results... */

        if (serviceResultString != null && serviceResultString.equals("") == false) {
            writeResponse(serviceResultString, responseFormat, callbackFunction, response);
        }

        println(">> Service script executed successfully.");

        /* Free the service instance... */

        freeServiceScript(service);

    } catch (Exception ex) {
        errorResponse(response, "Exception processing request: " + ex.toString(), responseFormat,
                callbackFunction);
        ex.printStackTrace();
        try {
            freeServiceScript(service);
        } catch (Exception x) {
            log.warn("Exception freeing a service instance: " + x.toString());
        }
        return;
    }

    println(">> Finished processRequest() at " + new Date());

}

From source file:com.castis.xylophone.adsmadapter.convert.axistree.ConvertMgad.java

@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
public int convertAdsInfo(AdsInfo adsInfo, AdsInfo unknownCategoryAdsInfo, String unknownCategoryfileName,
        String fileName, ADSMSchedulerLogDTO schedulerLog, ADSMSchedulerLogDTO deleteSchedulerLog,
        InputDataType inputDataType, PlacementOpportunityTypeEnum oppType, PlayInfo playInfo,
        Platform platformType, InventoryType inventoryType, String subDirectory) throws Exception {
    int resultCount = 0;
    long start = System.currentTimeMillis();
    log.info("convertAdsInfo start (" + oppType.name() + ", " + inventoryType.name() + ", "
            + platformType.name() + ")");

    this.fileName = fileName;
    campaignResult = new ResultFileUtil(InputDataType.ADS_INFO);
    exposurePolicyResult = new ResultFileUtil(InputDataType.EXPOSURE_POLICY);
    slotNumberPolicyResult = new ResultFileUtil(InputDataType.SLOT_NUMBER_POLICY);

    try {/*  w w  w .j a  v  a2s .c om*/
        if (adsInfo != null) {
            adsInfoResult = new ResultAdsInfo();
            adsInfoResult.setXml_ID(adsInfo.getXml_ID());
            adsInfoResult.setReg_DT(adsInfo.getReg_DT());

            try {
                timeDefineMap = tambourineConnector.getTimeDefineMap();
                if (timeDefineMap != null)
                    timeTreeNodeChildCount = tambourineConnector.getKTTimeTreeNodeChildCountMap(timeDefineMap);
            } catch (Exception e) {
                String error = "Time Define  load   . error : " + e.getMessage();
                log.error(error);
                throw new Exception(error);
            }

            if (inputDataType == InputDataType.ADS_INFO) {
                Date startTime = new Date(start);
                generateDisablePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType, playInfo,
                        platformType, inventoryType);
                /*!*/ generateSlotNumberPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                        oppType, playInfo, platformType, inventoryType);
                /*!*/ generateGroupRatePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                        playInfo, platformType, inventoryType);
                generateContinuosExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                        playInfo, platformType, inventoryType);
                generateExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                        oppType, playInfo, platformType, inventoryType);
                generateADProductPriorityPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                        playInfo, platformType, inventoryType);
                //AdCategory_dat
                generateDisableSameFieldADPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                        playInfo, platformType, inventoryType);
            }

            if (inputDataType == InputDataType.UPDATE_AD_POLICY) {
                Date startTime = new Date(start);
                generateSlotNumberPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                        oppType, playInfo, platformType, inventoryType);
                generateExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                        oppType, playInfo, platformType, inventoryType);
            }

            if (inputDataType != InputDataType.UPDATE_AD_POLICY)
                generateADCampaign(adsInfo, unknownCategoryAdsInfo, unknownCategoryfileName,
                        deleteSchedulerLog.getId(), inputDataType, schedulerLog, oppType, playInfo,
                        platformType, inventoryType);

            schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);
            deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);

            //Mgad   version  DB? ?.
            if (inputDataType == InputDataType.ADS_INFO) {
                String version = adsInfo.getAdsVersion();
                if (version == null || version.isEmpty())
                    version = NONE_VERSION;
                ImportSyncVersion importSyncVersion = new ImportSyncVersion(version, SyncType.ADS_SYNC,
                        schedulerLog.getId());
                tambourineConnector.mergeSyncVersion(importSyncVersion);
            }

            //update  ?  ??    ?, ? ?  ? ?? ? ?? .
            if (inputDataType != InputDataType.ADS_INFO) {
                if (campaignResult.getErrorCount() > 0 || exposurePolicyResult.getErrorCount() > 0
                        || slotNumberPolicyResult.getErrorCount() > 0)
                    resultCount = -1;
            } else
                resultCount = campaignResult.getErrorCount();

        } else {
            adsInfoResult = new ResultAdsInfo();
            adsInfoResult.setXml_ID("Parsing error");
            adsInfoResult.setReg_DT("Parsing error");
            log.error("mgad  ?(" + fileName
                    + ")  . Data ?  .");
            schedulerLog.setFailProcess("Parsing error");
            schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
            deleteSchedulerLog.setFailProcess("Parsing error");
            deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
            campaignResult.setErrorCount(-1); //Parsing error   
            exposurePolicyResult.setErrorCount(-1); //Parsing error   
            slotNumberPolicyResult.setErrorCount(-1); //Parsing error   
            resultCount = -1;
        }
    } catch (Exception e) {
        //log.error("",e);
        schedulerLog.setMessage(e.getMessage());
        schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
        StackTraceElement[] stackTraces = e.getStackTrace();
        if (stackTraces.length > 0) {
            schedulerLog.setFailProcess(stackTraces[0].getClassName() + " - " + stackTraces[0].getMethodName()
                    + "(" + stackTraces[0].getLineNumber() + ")");
        }
        resultCount = -1;
        throw e;
    } finally {
        ResultFileUtil.writeAdsResultFile(inputDataType, adsInfoResult, exposurePolicyResult,
                slotNumberPolicyResult, campaignResult, fileName, resultDirectory + subDirectory);
    }
    long end = System.currentTimeMillis();
    log.info("convertAdsInfo end - T(" + (end - start) + ") (" + oppType.name() + ")");

    return resultCount;
}

From source file:base.BasePlayer.FileRead.java

static String getVCFLine(String chrom, int start, int end, Sample sample) {
    if (Draw.variantcalculator) {
        return "";
    }//w  w w  . jav a 2 s. co m
    if (sample.calledvariants) {
        StringBuffer altbases = new StringBuffer("");
        int alts = 0, refs = 0;

        for (int i = 0; i < Main.drawCanvas.varOverLap.vars.size() - 1; i++) {
            altbases.append(Main.drawCanvas.varOverLap.vars.get(i).getKey());

        }
        alts = Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls();
        refs = (Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCoverage()
                - Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls());
        String genotype = "";
        if (alts / (double) refs > 0.95) {
            genotype = "1/1";
        } else {
            genotype = "0/1";
        }
        altbases.append(
                Main.drawCanvas.varOverLap.vars.get(Main.drawCanvas.varOverLap.vars.size() - 1).getKey());
        return Main.drawCanvas.splits.get(0).chrom + "\t" + (Main.drawCanvas.varOverLap.getPosition() + 1)
                + "\t.\t" + Main.getBase.get(Main.drawCanvas.varOverLap.getRefBase()) + "\t" + altbases
                + "\t99\tPASS\tINFO\tGT:AD:DP\t" + genotype + ":" + refs + "," + alts + ":" + (refs + alts);
    }
    String line = "";

    cancelfileread = false;
    cancelvarcount = false;

    try {
        if (!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) {
            if (sample.multipart) {
                for (int i = sample.getIndex(); i >= 0; i--) {
                    if (!Main.drawCanvas.sampleList.get(i).multipart) {
                        sample = Main.drawCanvas.sampleList.get(i);
                        break;
                    }
                }
            }
            if (sample.getTabixFile() != null) {

                setVCFFileStart(chrom, start, end + 3, sample);
                boolean vcf = sample.getVCFReader() != null;
                while (line != null) {
                    if (vcf) {
                        try {
                            sample.getVCFReader().ready();
                        } catch (IOException ex) {

                        }
                    }
                    try {
                        if (vcf) {

                            line = sample.getVCFReader().readLine();
                        } else {

                            line = sample.getVCFInput().readLine();
                        }
                        if (line == null || line.split("\t").length < 3 || line.startsWith("#")) {
                            continue;
                        }
                        if (line != null && Integer.parseInt(line.split("\t")[1]) == start + 1) {
                            if (sample.getVCFReader() != null) {
                                sample.getVCFReader().close();
                            }
                            return line;
                        }

                    } catch (Exception ex) {
                        Main.showError(ex.getMessage(), "Error");

                        ErrorLog.addError(ex.getStackTrace());
                        ex.printStackTrace();
                        Main.cancel();
                        changing = false;

                    }

                }

                if (sample.getVCFReader() != null) {
                    sample.getVCFReader().close();
                }

                return line;
            }
        }
    } catch (Exception exc) {
        Main.showError(exc.getMessage(), "Error");

        System.out.println(sample.getName());
        exc.printStackTrace();
        ErrorLog.addError(exc.getStackTrace());
        changing = false;
    }
    return "";
}

From source file:com.asksven.betterbatterystats.StatsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    super.onCreate(savedInstanceState);

    // HockeyApp/*from  w  ww .  ja v  a 2  s . co m*/
    try {
        MetricsManager.register(getApplication());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    //Log.i(TAG, "OnCreated called");
    setContentView(R.layout.stats);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayUseLogoEnabled(false);

    // set debugging
    if (sharedPrefs.getBoolean("debug_logging", false)) {
        LogSettings.DEBUG = true;
        CommonLogSettings.DEBUG = true;
    } else {
        LogSettings.DEBUG = false;
        CommonLogSettings.DEBUG = false;
    }

    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);

    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            doRefresh(true);
        }
    });

    ///////////////////////////////////////////////
    // check if we have a new release
    ///////////////////////////////////////////////
    // if yes do some migration (if required) and show release notes
    String strLastRelease = sharedPrefs.getString("last_release", "0");

    String strCurrentRelease = "";
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        strCurrentRelease = Integer.toString(pinfo.versionCode);
    } catch (Exception e) {
        // nop strCurrentRelease is set to ""
    }

    // Grant permissions if they are missing and root is available
    if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
            || !SysUtils.hasPackageUsageStatsPermission(this)) {
        if ((RootShell.getInstance().isRooted())) {

            // attempt to set perms using pm-comand
            Log.i(TAG, "attempting to grant perms with 'pm grant'");

            String pkg = this.getPackageName();
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.BATTERY_STATS");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.DUMP");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.PACKAGE_USAGE_STATS");

            if (SysUtils.hasBatteryStatsPermission(this)) {
                Log.i(TAG, "succeeded");
            } else {
                Log.i(TAG, "failed");
            }
        }
    }

    // Package usage stats were introduced in SDK21 so we need to make the distinction
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // show install as system app screen if root available but perms missing
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
                || !SysUtils.hasPackageUsageStatsPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }
    } else {
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }

    }
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // first start
    if (strLastRelease.equals("0")) {

        boolean firstLaunch = !prefs.getBoolean("launched", false);

        if (firstLaunch) {
            // Save that the app has been launched
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("launched", true);
            editor.commit();

            // start service to persist reference
            Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
            this.startService(serviceIntent);

            // refresh widgets
            Intent intentRefreshWidgets = new Intent(LargeWidgetProvider.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);

        }

        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    } else if (!strLastRelease.equals(strCurrentRelease)) {
        // save the current release to properties so that the dialog won't be shown till next version
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();

        // we don't need to delete refs as long as we don't change the database schema
        //         Toast.makeText(this, getString(R.string.info_deleting_refs), Toast.LENGTH_SHORT).show();
        //         ReferenceStore.deleteAllRefs(this);
        //         Intent i = new Intent(this, WriteBootReferenceService.class);
        //         this.startService(i);
        //         i = new Intent(this, WriteUnpluggedReferenceService.class);
        //         this.startService(i);
        ChangeLog cl = new ChangeLog(this);
        cl.getLogDialog().show();

    }

    ///////////////////////////////////////////////
    // retrieve default selections for spinners
    // if none were passed
    ///////////////////////////////////////////////

    m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
    m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

    if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) {

        m_refFromName = Reference.BOOT_REF_FILENAME;
        Toast.makeText(this, getString(R.string.info_fallback_to_boot), Toast.LENGTH_SHORT).show();
    }

    if (LogSettings.DEBUG)
        Log.i(TAG, "onCreate state from preferences: refFrom=" + m_refFromName + " refTo=" + m_refToName);

    try {
        // recover any saved state
        if ((savedInstanceState != null) && (!savedInstanceState.isEmpty())) {
            m_iStat = (Integer) savedInstanceState.getSerializable("stat");
            m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
            m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");

            if (LogSettings.DEBUG)
                Log.i(TAG,
                        "onCreate retrieved saved state: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        }
    } catch (Exception e) {
        m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
        m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

        Log.e(TAG, "Exception: " + e.getMessage());
        DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
        DataStorage.LogToFile(LOGFILE, e.getMessage());
        DataStorage.LogToFile(LOGFILE, e.getStackTrace());

        Toast.makeText(this, getString(R.string.info_state_recovery_error), Toast.LENGTH_SHORT).show();
    }

    // Handle the case the Activity was called from an intent with paramaters
    Bundle extras = getIntent().getExtras();
    if ((extras != null) && !extras.isEmpty()) {
        // Override if some values were passed to the intent
        if (extras.containsKey(StatsActivity.STAT))
            m_iStat = extras.getInt(StatsActivity.STAT);
        if (extras.containsKey(StatsActivity.STAT_TYPE_FROM))
            m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
        if (extras.containsKey(StatsActivity.STAT_TYPE_TO))
            m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);

        if (LogSettings.DEBUG)
            Log.i(TAG, "onCreate state from extra: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);

        // Clear the notifications that was clicked to call the activity
        if (bCalledFromNotification) {
            NotificationManager nM = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            nM.cancel(EventWatcherService.NOTFICATION_ID);
        }
    }

    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);

    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats,
            R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); // android.R.layout.simple_spinner_dropdown_item);

    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the Stat type
    ///////////////////////////////////////////////
    Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
    m_spinnerFromAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerFromAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);
    spinnerStatType.setAdapter(m_spinnerFromAdapter);

    try {
        this.setListViewAdapter();
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Snackbar.make(findViewById(android.R.id.content), R.string.info_service_connection_error,
                Snackbar.LENGTH_LONG).show();
        //         Toast.makeText(this,
        //               getString(R.string.info_service_connection_error),
        //               Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        //Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Toast.makeText(this, getString(R.string.info_unknown_stat_error), Toast.LENGTH_LONG).show();
    }
    // setSelection MUST be called after setAdapter
    spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
    spinnerStatType.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the end sample
    ///////////////////////////////////////////////
    Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
    m_spinnerToAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerToAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);

    spinnerStatSampleEnd.setVisibility(View.VISIBLE);
    spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
    // setSelection must be called after setAdapter
    if ((m_refToName != null) && !m_refToName.equals("")) {
        int pos = m_spinnerToAdapter.getPosition(m_refToName);
        spinnerStatSampleEnd.setSelection(pos);

    } else {
        spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
    }

    spinnerStatSampleEnd.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // sorting
    ///////////////////////////////////////////////
    m_iSorting = 0;

    // log reference store
    ReferenceStore.logReferences(this);

    if (LogSettings.DEBUG) {
        Log.i(TAG, "onCreate final state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        Log.i(TAG, "OnCreated end");
    }

}

From source file:base.BasePlayer.FileRead.java

static void annotate() {

    if (Main.drawCanvas.splits.get(0).getGenes().size() == 0) {
        return;//from w  w w.  j a v a 2s  .  co  m
    }
    Transcript transcript;
    Gene gene, prevGene = Main.drawCanvas.splits.get(0).getGenes().get(0);
    VarNode current = FileRead.head.getNext();
    Transcript.Exon exon;
    int position = 0, baselength;

    boolean intronic = true;
    try {

        if (current != null) {

            for (int g = 0; g < Main.drawCanvas.splits.get(0).getGenes().size(); g++) {
                gene = Main.drawCanvas.splits.get(0).getGenes().get(g);

                /*   while(current != null && current.getPosition() < gene.getStart()) {
                      if(!current.isInGene()) {
                         if(current.getTranscripts() == null) {
                            current.setTranscripts();
                         }               
                         current.getTranscripts().add(prevGene.getTranscripts().get(0));
                         current.getTranscripts().add(gene.getTranscripts().get(0));
                      }
                      current = current.getNext();
                   }*/

                if (current == null) {
                    break;
                }

                for (int t = 0; t < gene.getTranscripts().size(); t++) {
                    transcript = gene.getTranscripts().get(t);

                    if (current != null && current.getPrev() != null) {

                        while (current.getPrev().getPosition() >= transcript.getStart()) {

                            if (current.getPrev() != null) {
                                current = current.getPrev();
                            }

                        }
                    }

                    position = current.getPosition();

                    if (current.indel) {
                        position++;
                        baselength = MethodLibrary.getBaseLength(current.vars, 1);
                    }
                    while (position < transcript.getEnd()) {

                        try {
                            if (position >= transcript.getStart() && position <= transcript.getEnd()) {

                                current.setInGene();

                                baselength = 0;
                                intronic = true;

                                for (int e = 0; e < transcript.getExons().length; e++) {

                                    exon = transcript.getExons()[e];

                                    if (position + baselength >= exon.getStart() - 2
                                            && position < exon.getEnd() + 2) {
                                        if (current.getExons() == null) {
                                            current.setExons();
                                        }

                                        intronic = false;
                                        if (!current.getExons().contains(exon)) {

                                            current.getExons().add(exon);
                                            if (exon.getStartPhase() > -1
                                                    && position + baselength >= exon.getTranscript()
                                                            .getCodingStart()
                                                    && position < exon.getTranscript().getCodingEnd()) {
                                                current.coding = true;
                                            }
                                            break;
                                        }
                                    }

                                }
                                if (intronic) {
                                    if (current.getTranscripts() == null) {
                                        current.setTranscripts();
                                    }

                                    current.getTranscripts().add(transcript);

                                }
                            }
                            if (!current.isInGene()) {
                                if (current.getTranscripts() == null) {
                                    current.setTranscripts();
                                    current.getTranscripts().add(prevGene.getTranscripts().get(0));
                                    current.getTranscripts().add(gene.getTranscripts().get(0));

                                }
                            }

                            if (current.getNext() != null) {
                                current = current.getNext();
                                position = current.getPosition();
                            } else {

                                break;
                            }
                        } catch (Exception e) {
                            System.out.println(position);
                            e.printStackTrace();
                            break;
                        }
                    }
                }

                if (gene.getEnd() > prevGene.getEnd()) {

                    prevGene = gene;
                }

            }
            while (current != null) {
                if (!current.isInGene()) {
                    if (current.getTranscripts() == null) {
                        current.setTranscripts();
                        current.getTranscripts().add(prevGene.getTranscripts().get(0));
                        current.getTranscripts().add(prevGene.getTranscripts().get(0));
                    }

                }
                current = current.getNext();
            }
        }
    } catch (Exception e) {
        ErrorLog.addError(e.getStackTrace());
        e.printStackTrace();

    }
    current = null;
    transcript = null;
    exon = null;
}

From source file:base.BasePlayer.FileRead.java

void readBED(String url, String index, boolean small) {

    try {// w  ww .j av  a  2 s.c o m

        if (!Main.trackPane.isVisible()) {
            Main.trackPane.setVisible(true);
            Main.varpane.setDividerSize(3);
            Main.varpane.setResizeWeight(0.1);
            Main.varpane.setDividerLocation(0.1);

        } else {
            Main.varpane.setDividerLocation(Main.varpane.getDividerLocation() + 100);
            Main.varpane.revalidate();
            Main.trackPane.setDividerLocation(Main.varpane.getDividerLocation() / 2);

            if (Main.controlScroll.isVisible()) {
                Main.trackPane.setDividerSize(3);
            }
        }
        Main.bedScroll.setVisible(true);
        Main.bedCanvas.setVisible(true);
        BedTrack addTrack = null;
        if (index.equals("nan")) {

            addTrack = new BedTrack(new URL(url), null, Main.bedCanvas.bedTrack.size());

        } else {
            addTrack = new BedTrack(new URL(url), new URL(index), Main.bedCanvas.bedTrack.size());
        }

        //Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd);   
        if (addTrack != null) {
            if (url.toLowerCase().endsWith("tsv.gz") || url.toLowerCase().endsWith("tsv.bgz")) {
                addTrack.getZerobased().setSelected(false);
                addTrack.iszerobased = 1;
                addTrack.getSelector().frame.setVisible(true);
            }
            addTrack.small = small;
            Main.bedCanvas.trackDivider.add(0.0);
            Main.bedCanvas.bedTrack.add(addTrack);
            setTable(addTrack);
            if (url.toLowerCase().endsWith(".bedgraph")) {
                Main.bedCanvas.pressGraph(addTrack);
            }
            if (url.toLowerCase().endsWith("bigwig") || url.toLowerCase().endsWith("bw")) {
                addTrack.small = true;
                addTrack.bigWig = true;
                addTrack.graph = true;
                //Main.bedCanvas.getBEDfeatures(addTrack, (int)Main.drawCanvas.splits.get(0).start, (int)Main.drawCanvas.splits.get(0).end);         
            }
            setBedTrack(addTrack);
            if (addTrack.small) {
                // Main.drawCanvas.loading("loading");
                Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd);

                //Main.drawCanvas.ready("loading");
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
        ErrorLog.addError(e.getStackTrace());
    }
}

From source file:base.BasePlayer.FileRead.java

private void readBAM(File[] files) {
    try {/*from   w ww. j  a  v a 2s  .  c o  m*/

        File addFile = null;
        File[] addDir;
        Sample currentSample = null;
        Boolean added = false;

        if (files.length == 1 && files[0].getName().endsWith(".link")) {
            files = readLinkFile(files[0]);
        }

        for (int i = 0; i < files.length; i++) {

            if (files[i].isDirectory()) {
                addDir = files[i].listFiles();
                for (int f = 0; f < addDir.length; f++) {
                    if (addDir[f].getName().endsWith(".bam") || addDir[f].getName().endsWith(".cram")) {
                        addFile = addDir[f];
                        break;
                    }
                }
            } else {
                if (files[i].getName().endsWith(".bam") || files[i].getName().endsWith(".cram")) {
                    addFile = files[i];
                } else {
                    continue;
                }
            }

            if (addFile != null) {
                Main.drawCanvas.bam = true;
                currentSample = new Sample(addFile.getName(), (short) Main.samples, null);
                Main.drawCanvas.sampleList.add(currentSample);
                currentSample.samFile = addFile;
                currentSample.resetreadHash();
                if (addFile.getName().endsWith(".cram")) {
                    currentSample.CRAM = true;
                }

                if (currentSample.samFile.getName().endsWith(".cram")) {
                    currentSample.readString = "CRAM";
                } else {
                    currentSample.readString = "BAM";
                }
                try {

                } catch (Exception e) {
                    ErrorLog.addError(e.getStackTrace());
                    e.printStackTrace();
                }
                added = true;
                Main.readsamples++;
                Main.samples++;
            }

        }
        if (!added) {
            return;
        }
        checkSamples();
        Main.drawCanvas.drawVariables.visiblesamples = (short) (Main.samples);
        //    Main.drawCanvas.checkSampleZoom();

        if (Main.drawScroll.getViewport().getHeight()
                / (Main.drawCanvas.sampleList.size()) > Draw.defaultSampleHeight) {
            Main.drawCanvas.drawVariables.sampleHeight = Main.drawScroll.getViewport().getHeight()
                    / Main.drawCanvas.sampleList.size();
        } else {
            Main.drawCanvas.drawVariables.sampleHeight = Draw.defaultSampleHeight;
        }

        if (Main.drawCanvas.getHeight() < (Main.drawCanvas.sampleList.size())
                * Main.drawCanvas.drawVariables.sampleHeight) {

            Main.drawCanvas.resizeCanvas(Main.drawCanvas.getWidth(),
                    (int) ((Main.drawCanvas.sampleList.size()) * Main.drawCanvas.drawVariables.sampleHeight));
            Main.drawCanvas.revalidate();
        }
    } catch (Exception e) {
        ErrorLog.addError(e.getStackTrace());
        e.printStackTrace();
    }
    Draw.updateReads = true;
    Draw.updatevars = true;
    Main.drawCanvas.repaint();
}