Example usage for java.text ParseException getClass

List of usage examples for java.text ParseException getClass

Introduction

In this page you can find the example usage for java.text ParseException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.sakaiproject.profile2.util.ProfileUtils.java

/**
 * Convert a string into a Date object (reverse of above
 *
 * @param dateStr      date string to convert
 * @param format      format of the input date in SimpleDateFormat syntax
 *//* w  w  w  .  j av  a2s .  co  m*/
public static Date convertStringToDate(String dateStr, String format) {
    if ("".equals(dateStr) || "".equals(format)) {
        throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()");
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat(format);

    try {
        Date date = dateFormat.parse(dateStr);

        log.debug("Profile.convertStringToDate(): Input date string: " + dateStr);
        log.debug("Profile.convertStringToDate(): Converted date: " + date.toString());
        return date;
    } catch (ParseException e) {
        log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage());
        return null;
    }
}

From source file:org.gbif.dwca.action.ValidateAction.java

@Override
public String execute() {
    ArchiveLocation archLoc = null;/*from www.j a va 2 s .co  m*/
    try {
        if (!StringUtils.isBlank(ifModifiedSince)) {
            ifModifiedSinceDate = DateFormatUtils.ISO_DATE_FORMAT.parse(ifModifiedSince);
            if (ifModifiedSinceDate == null) {
                log.debug("Use conditional get for download if modified since: " + ifModifiedSince);
                return INPUT;
            }
        }

        archLoc = extractArchive();
        if (archLoc == null && status == null) {
            return INPUT;
        }
        if (archLoc != null) {
            extensions = extensionManager.map();
            validateAgainstSchema(archLoc.metaFile);
            validateArchive(archLoc.dwcaFolder);
        }
    } catch (ParseException e) {
        setOffline("Invalid ISO date " + e.getMessage());
    } catch (MalformedURLException e) {
        setOffline("MalformedURLException " + e.getMessage());
    } catch (SocketException e) {
        setOffline(e.getClass().getSimpleName() + " " + e.getMessage());
    } catch (Exception e) {
        log.error("Unknown error when validating archive", e);
        valid = false;
    } finally {
        // cleanup temp files!
        cleanupTempFile(archLoc);
    }

    // store html report
    if (archLoc != null) {
        storeReport();
    }

    return SUCCESS;
}

From source file:pro.dbro.bart.BartRouteParser.java

@Override
protected routeResponse doInBackground(String... input) {
    final routeResponse response = new routeResponse();
    //convert string into input stream for xml parsing
    ByteArrayInputStream bais = new ByteArrayInputStream(input[0].getBytes());

    IRule originStationRule = new DefaultRule(Type.CHARACTER, "/root/origin") {
        @Override//from  w  ww  .j  a  v a 2 s .c o  m
        public void handleParsedCharacters(XMLParser parser, String text, Object userObject) {
            response.originStation = text;
        }
    };
    IRule destinationStationRule = new DefaultRule(Type.CHARACTER, "/root/destination") {
        @Override
        public void handleParsedCharacters(XMLParser parser, String text, Object userObject) {
            response.destinationStation = text;
        }
    };
    IRule timeRule = new DefaultRule(Type.CHARACTER, "/root/schedule/time") {
        @Override
        public void handleParsedCharacters(XMLParser parser, String text, Object userObject) {
            responseTime = text;
        }
    };
    IRule dateRule = new DefaultRule(Type.CHARACTER, "/root/schedule/date") {
        @Override
        public void handleParsedCharacters(XMLParser parser, String text, Object userObject) {
            responseDate = text;
        }
    };
    IRule specialScheduleRule = new DefaultRule(Type.CHARACTER, "/root/message/special_schedule") {
        @Override
        public void handleParsedCharacters(XMLParser parser, String text, Object userObject) {
            //fix for BART returning relative, not absolute, links
            response.specialSchedule = text.replace("href=\"/", "href=\"http://bart.gov/");
        }
    };
    // origin="DBRK" destination="WCRK" fare="3.15" origTimeMin="3:18 PM" origTimeDate="03/16/2012 " destTimeMin="3:44 PM" destTimeDate="03/16/2012"
    IRule tripAttributeRule = new DefaultRule(Type.ATTRIBUTE, "/root/schedule/request/trip",
            new String[] { "fare", "origTimeMin", "origTimeDate", "destTimeMin", "destTimeDate" }) {
        @Override
        public void handleParsedAttribute(XMLParser parser, int num, String value, Object userObject) {

            //("ATTRIBUTE",String.valueOf(num)+ " - "+value);
            if (num == 0) { // fare
                route thisRoute = response.addRoute();
                thisRoute.fare = value;
                //leg thisLeg = thisRoute.addLeg();
                //thisLeg.disembarkStation = TheActivity.STATION_MAP.get(value);
            } else if (num == 1) { // origTimeMin
                routeOriginTime = value;
            } else if (num == 2) {
                routeOriginDate = value;
            } else if (num == 3) {
                routeDestinationTime = value;
                //("ROUTE_DEST_TIME",value.toString());
            } else if (num == 4) {
                //Log.v("ROUTE_DEST_DATE",value.toString());
                routeDestinationDate = value;
            }
            //thisRoute.fare
        }
    };
    IRule tripTagRule = new DefaultRule(Type.TAG, "/root/schedule/request/trip") {
        @Override
        public void handleTag(XMLParser parser, boolean isStartTag, Object userObject) {
            if (!isStartTag) {
                route thisRoute = response.getLastRoute();

                // Determine if bikes are allowed on all legs of this route
                boolean bikes = true;
                for (int x = 0; x < thisRoute.legs.size(); x++) {
                    if (!((leg) thisRoute.legs.get(x)).bikes)
                        bikes = false;
                }
                thisRoute.bikes = bikes;

                String originDateStr = routeOriginDate + " " + routeOriginTime;
                String destinationDateStr = routeDestinationDate + " " + routeDestinationTime;
                // Bart Route responses don't indicate timezone (?), though etd responses do
                // Set SimpleDateFormat TimeZone to America/Los-Angeles
                // This ensures the application can correctly combine etd responses (with timezone) and route (without)
                // Even if the application is run on a device who's locale differs from BARTs (PST)
                curFormater = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
                curFormater.setTimeZone(tz);
                try {
                    Log.d("BartRouteParserEndTrip",
                            "originDate: " + originDateStr + " destDate: " + destinationDateStr);
                    thisRoute.departureDate = curFormater.parse(originDateStr);//append BART response timezone
                    thisRoute.arrivalDate = curFormater.parse(destinationDateStr);//append BART response timezone
                } catch (ParseException e) {
                    Log.d("BartRouteParserEndTrip", "non-PDT coerced parse failed");
                    // TODO Auto-generated catch block
                    // 5.15.2012: I've received multiple crashes here. Something's going on related to irregular time format...
                    // IF coercing PDT fails, try without at the risk of displaying incorrect time
                    /*try{
                       Crittercism.leaveBreadcrumb(Log.getStackTraceString(e));
                       thisRoute.departureDate = curFormater.parse(originDateStr);
                       thisRoute.arrivalDate = curFormater.parse(destinationDateStr);
                    }
                    catch(ParseException e2){*/
                    Log.d("BartRouteParserEndTrip", "non-PST coerced parse failed");
                    Log.d("BartRouteParserEndTrip_DateString",
                            "origin: " + originDateStr + " , destination: " + destinationDateStr);
                    Log.d("BartRouteParserEndTripException", e.getClass().toString() + ": " + e.getMessage());
                    Crittercism.leaveBreadcrumb(originDateStr + " , " + destinationDateStr);
                    Crittercism.leaveBreadcrumb(Log.getStackTraceString(e));
                    Crittercism.logHandledException(e);
                    dateError = true;
                    //}
                }
                if (!dateError)
                    Log.d("RouteParserDate", "depart: " + thisRoute.departureDate.toString() + " arrive: "
                            + thisRoute.arrivalDate.toString());
                else {
                    // if an improper date is given, remove this route from response
                    response.removeLastRoute();
                }
                // reset these variables for use by the next route
                originDateStr = "";
                destinationDateStr = "";
            }

        }
    };
    //
    IRule legAttributeRule = new DefaultRule(Type.ATTRIBUTE, "/root/schedule/request/trip/leg",
            new String[] { "transfercode", "origin", "destination", "origTimeMin", "origTimeDate",
                    "destTimeMin", "destTimeDate", "trainHeadStation", "bikeflag" }) {
        @Override
        public void handleParsedAttribute(XMLParser parser, int num, String value, Object userObject) {
            // TODO: Fix assumed order of XML attributes
            route thisRoute;
            leg thisLeg;
            String dateStr;
            switch (num) {
            case 0:// transfercode
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.addLeg();
                thisLeg.transferCode = value;
                break;
            //leg thisLeg = thisRoute.addLeg();
            //thisLeg.disembarkStation = TheActivity.STATION_MAP.get(value);

            case 1: // orig station
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                thisLeg.boardStation = value;
                break;

            case 2: // dest station
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                thisLeg.disembarkStation = value;
                break;

            case 3: // board time
                legTime = value;
                break;

            case 4: // board date
                legDate = value;
                dateStr = legDate + " " + legTime;
                curFormater = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
                curFormater.setTimeZone(tz);
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                try {
                    thisLeg.boardTime = curFormater.parse(dateStr);
                } catch (ParseException e) {
                    Log.d("BartRouteParser", "boardTime unparseable: " + dateStr);
                    e.printStackTrace();
                }
                break;

            case 5: // dest time
                legTime = value;
                break;

            case 6: // dest date
                legDate = value;
                //assume date always follows time:
                dateStr = legDate + " " + legTime;
                curFormater = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
                curFormater.setTimeZone(tz);
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                try {
                    thisLeg.disembarkTime = curFormater.parse(dateStr);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    Log.d("BartRouteParser", "disembarkTime unparseable: " + dateStr);
                    e.printStackTrace();
                }
                break;

            case 7: // train head station
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                thisLeg.trainHeadStation = value.toLowerCase();
                break;

            case 8: // bikeFlag
                thisRoute = response.getLastRoute();
                thisLeg = thisRoute.getLastLeg();
                if (value.equals("1"))
                    thisLeg.bikes = true;
                else
                    thisLeg.bikes = false;
                break;
            }

        }
    };

    XMLParser parser = new XMLParser(originStationRule, destinationStationRule, timeRule, dateRule,
            tripAttributeRule, tripTagRule, legAttributeRule, specialScheduleRule);
    try {
        parser.parse(bais);
    } catch (XMLParserException e) {
        // Send a message to TheActivity to display an error dialog
        // Then cancel this AsyncTask
        sendError("Open BART received a malformed response. Please try again.");
        this.cancel(true);
    }
    //11:15:32 AM PDT

    //String[] timesplit = time.split(" ");
    String dateStr = responseDate + " " + responseTime;
    //Log.v("time split", timesplit.toString());
    //Log.v("Time",dateStr);
    curFormater = new SimpleDateFormat("MMM dd, yyyy hh:mm a", Locale.US);
    curFormater.setTimeZone(tz);
    Date dateObj = new Date();
    try {
        dateObj = curFormater.parse(dateStr);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        //Log.v("XMLParse", "date formatting error");
        Log.d("BartRouteParser", "Response date parse error");
        e.printStackTrace();
    }
    response.date = dateObj;

    return response;
}

From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java

/**
 * Get metric sla result/*from  w w  w. j a va2s . co m*/
 * 
 * @param metricSlaId
 * @param startDate
 * @param endDate
 * @return MetricSLAResult
 */
@Override
public MetricSLAResult getMetricSlaResult(Integer metricSlaId, Date startDate, Date endDate) {
    MetricSLAResult metricSlaResult = new MetricSLAResult();

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Double actualPercentage = null;

        MetricSLAState metricSlaState = MetricSLAState.NO_DATA;

        MetricSLA metricSla = new MetricSLA();
        metricSla = this.getMetricSla(metricSlaId, null);

        // Get alarm status history for this sla
        ArrayList<MetricSlaAlarmStatus> metricSlaAlarmStatusList = new ArrayList<MetricSlaAlarmStatus>();
        metricSlaAlarmStatusList = this.getMetricSlaAlarmStatus(metricSlaId, startDate, endDate);

        if (metricSlaAlarmStatusList.size() > 0) {
            Double totalAlarmCount = 0.0;

            for (MetricSlaAlarmStatus m : metricSlaAlarmStatusList) {
                // Get total count of when alarm been raised
                if (m.getAlarmState().equals(AlarmState.OK)) {
                    totalAlarmCount += 1;
                }
            }

            // Calculate sla percentage
            Double metricSlaAlarmStatusCount = (double) metricSlaAlarmStatusList.size();
            actualPercentage = totalAlarmCount / metricSlaAlarmStatusCount * 100.0;

            if (actualPercentage >= metricSla.getPercentage()) {
                metricSlaState = MetricSLAState.IN_SLA;
            } else {
                metricSlaState = MetricSLAState.OUT_SLA;
            }

        } else {
            metricSlaState = MetricSLAState.NO_DATA;
            actualPercentage = 0.0;
        }

        metricSlaResult.setMetricSLA(metricSla);
        metricSlaResult.setMetricSLAState(metricSlaState);
        metricSlaResult.setStartDate(sdf.parse(sdf.format(date)));
        metricSlaResult.setStartDate(startDate);
        metricSlaResult.setEndDate(endDate);
        metricSlaResult.setSlaPercentage(actualPercentage);

    } catch (ParseException e) {
        this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage());
        e.printStackTrace();
    }
    return metricSlaResult;
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

/**
 * Only works if we have path to GIT/*  w  w  w  .  jav  a  2s.c om*/
 */
public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);

    // -w is to ignore whitespace bug
    ProcessBuilder processBuilder = new ProcessBuilder(this.GIT_BINARY_PATH, "blame", "-c", "-w", fileName);
    // The / part is required due to centos bug for version 1.1.1
    processBuilder.directory(new File(repoLocations + "/" + repoName));

    Process process = null;
    BufferedReader bufferedReader = null;

    try {
        process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, Values.CHARSET_UTF8);
        bufferedReader = new BufferedReader(isr);
        String line;
        DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");

        HashMap<String, CodeOwner> owners = new HashMap<>();

        boolean foundSomething = false;

        while ((line = bufferedReader.readLine()) != null) {
            Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
            String[] split = line.split("\t");

            if (split.length > 2 && split[1].length() != 0) {
                foundSomething = true;
                String author = split[1].substring(1);
                int commitTime = (int) (System.currentTimeMillis() / 1000);
                try {
                    commitTime = (int) (df.parse(split[2]).getTime() / 1000);
                } catch (ParseException ex) {
                    Singleton.getLogger().info("time parse expection for " + repoName + fileName);
                }

                if (owners.containsKey(author)) {
                    CodeOwner codeOwner = owners.get(author);
                    codeOwner.incrementLines();

                    int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                    if (commitTime > timestamp) {
                        codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
                    }
                    owners.put(author, codeOwner);
                } else {
                    owners.put(author, new CodeOwner(author, 1, commitTime));
                }
            }
        }

        if (foundSomething == false) {
            // External call for CentOS issue
            String[] split = fileName.split("/");

            if (split.length != 1) {
                codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations,
                        String.join("/", Arrays.asList(split).subList(1, split.length)));
            }

        } else {
            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException | StringIndexOutOfBoundsException ex) {
        Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
        Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
        Singleton.getLogger()
                .warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                        + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: "
                        + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(process);
        Singleton.getHelpers().closeQuietly(bufferedReader);
    }

    return codeOwners;
}

From source file:ezbake.services.search.SSRServiceHandler.java

@Override
public PercolatorHitInbox getAndFlushPercolatorInbox(String percolatorId, EzSecurityToken userToken)
        throws TException {
    AuditEvent evt = event(AuditEventType.FileObjectModify.getName(), userToken).arg("event",
            "getAndFlushPercolatorInbox");
    EzElastic.Client documentClient = null;
    try {/*from w  w  w .j  ava2 s. com*/
        // Get the inbox from EzElastic
        userToken = validateAndFetchDerived(userToken);
        PercolatorHitInbox result = new PercolatorHitInbox();
        String inboxId = getPercolatorInboxId(percolatorId);
        Document percolatorInboxResponse = null;
        try {
            documentClient = getDocumentClient();
            percolatorInboxResponse = documentClient.getWithType(inboxId,
                    SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_TYPE_FIELD, userToken);
        } finally {
            documentClient = returnAndNullClient(documentClient);
        }
        if (percolatorInboxResponse.get_id() == null)
            throw new TException("Could not get the percolatorInbox for this percolator id:" + percolatorId);

        // Get the lastFlush date from the inbox
        JSONObject jsonObject = new JSONObject(percolatorInboxResponse.get_jsonObject());
        String lastFlushedString = jsonObject.getString(SSRUtils.PERCOLAOTR_INDIVIDUAL_INBOX_LAST_FLUSHED);
        SimpleDateFormat ingestFormatter = new SimpleDateFormat(SSR_DEFAULT_DATE_FORMAT);
        Date lastFlushedDate = ingestFormatter.parse(lastFlushedString);
        result.setLastFlushed(TimeUtil.convertToThriftDateTime(lastFlushedDate.getTime()));
        boolean exceedsLimit = false;
        if (jsonObject.has(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_EXCEEDS_LIMIT)) {
            exceedsLimit = jsonObject.getBoolean(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_EXCEEDS_LIMIT);
        }
        result.setExceedLimit(exceedsLimit);

        // Get the array of document hit
        JSONArray hitArray = jsonObject.getJSONArray(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_DOC_HITS);

        // the query to query SSR by ids
        IdsQueryBuilder idsQueryBuilder = QueryBuilders.idsQuery();

        for (int i = 0; i < hitArray.length(); i++) {
            // prepare the doc ids to query again for SSR
            String documentId = hitArray.getJSONObject(i)
                    .getString(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_DOC_ID);
            idsQueryBuilder.addIds(documentId);
        }

        // query the matching SSRs from database again
        try {
            documentClient = getDocumentClient();

            Query query = new Query(idsQueryBuilder.toString());
            query.setReturnedFields(ImmutableSet.of(SSRUtils.SSR_FIELD));
            // we want all the documents
            query.setPage(new Page(0, (short) hitArray.length()));
            // set the facets
            query.setFacets(buildSSRFacets());
            // we care only documents have ssr field
            addExistSSRFilter(query);
            SearchResult ssrResults = documentClient.query(query, userToken);

            // The matching ssr results for document hits
            result.setHits(processSsrSearchResult(ssrResults, (short) ssrResults.getTotalHits(), 0));
        } finally {
            documentClient = returnAndNullClient(documentClient);
        }

        // Set the last flush date to the current date
        jsonObject.put(SSRUtils.PERCOLAOTR_INDIVIDUAL_INBOX_LAST_FLUSHED, ingestFormatter.format(new Date()));
        jsonObject.put(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_DOC_HITS, new JSONArray());
        // Clear exceedLimit flag
        jsonObject.put(SSRUtils.PERCOLATOR_INDIVIDUAL_INBOX_EXCEEDS_LIMIT, false);
        percolatorInboxResponse.set_jsonObject(jsonObject.toString());
        IndexResponse inboxFlushingResponse = null;
        try {
            documentClient = getDocumentClient();
            inboxFlushingResponse = documentClient.put(percolatorInboxResponse, userToken);
        } finally {
            documentClient = returnAndNullClient(documentClient);
        }
        if (!inboxFlushingResponse.isSuccess())
            logError(new TException("getAndFlushPercolatorInbox failed to update the inbox"), evt,
                    "getAndFlushPercolatorInbox failed to update the inbox");
        return result;

    } catch (ParseException e) {
        logError(e, evt, "getAndFlushPercolatorInbox encountered an exception [" + e.getClass().getName() + ":"
                + e.getMessage() + "]");
        throw new TException(e);
    } catch (Exception e) {
        logError(e, evt, "getAndFlushPercolatorInbox encountered an exception [" + e.getClass().getName() + ":"
                + e.getMessage() + "]");
        throw e;
    } finally {
        returnAndNullClient(documentClient);
        auditLogger.logEvent(evt);
    }
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

/**
 * Only works if we have path to GIT// w w  w  .j  a v  a2 s . co m
 */
private List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);

    try {
        // -w is to ignore whitespace bug
        ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName);
        // The / part is required due to centos bug for version 1.1.1
        processBuilder.directory(new File(repoLocations + "/" + repoName));

        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");

        HashMap<String, CodeOwner> owners = new HashMap<>();

        boolean foundSomething = false;

        while ((line = br.readLine()) != null) {
            Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
            String[] split = line.split("\t");

            if (split.length > 2 && split[1].length() != 0) {
                foundSomething = true;
                String author = split[1].substring(1);
                int commitTime = (int) (System.currentTimeMillis() / 1000);
                try {
                    commitTime = (int) (df.parse(split[2]).getTime() / 1000);
                } catch (ParseException ex) {
                    Singleton.getLogger().info("time parse expection for " + repoName + fileName);
                }

                if (owners.containsKey(author)) {
                    CodeOwner codeOwner = owners.get(author);
                    codeOwner.incrementLines();

                    int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                    if (commitTime > timestamp) {
                        codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
                    }
                    owners.put(author, codeOwner);
                } else {
                    owners.put(author, new CodeOwner(author, 1, commitTime));
                }
            }
        }

        if (foundSomething == false) {
            // External call for CentOS issue
            String[] split = fileName.split("/");

            if (split.length != 1) {
                codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations,
                        String.join("/", Arrays.asList(split).subList(1, split.length)));
            }

        } else {
            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException | StringIndexOutOfBoundsException ex) {
        Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
        Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return codeOwners;
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryFieldPanel.java

/**
 * @return/*from  www .j  a v a2 s  . co  m*/
 */
@SuppressWarnings("unchecked")
public String getCriteriaFormula(final TableAbbreviator ta, final List<Pair<String, Object>> paramList)
        throws ParseException {
    if (operatorCBX.getSelectedItem().equals(SpQueryField.OperatorType.EMPTY)) {
        boolean isNot = isNotCheckbox.isSelected();
        String nullCond = fieldQRI.getNullCondition(ta, schemaItem != null, isNot, getFormatName());
        if (fieldQRI.getDataClass().equals(String.class)) {
            String fieldSpec = fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName());
            return "(" + nullCond + (isNot ? " and " : " or ") + fieldSpec + (isNot ? " <> " : " = ") + "'')";
        }
        return nullCond;
    }

    if (hasCriteria()) {
        boolean addNullConjunction = false;
        boolean nullPick = criteria instanceof PickListCriteriaCombo
                && ((PickListCriteriaCombo) criteria).nullItemIsPicked();
        Object[] criteriaStrs = parseCriteria(getCriteriaText(true).trim());
        String criteriaFormula = "";
        //String operStr = operatorCBX.getSelectedItem().toString();
        String operStr = getOperatorQLText();
        if (!(criteriaStrs[0] instanceof String) && !(criteriaStrs[0] instanceof Pair)) {
            //XXX - If the field has a formatter and it returned non-String data
            // then assume all parsing and conversion has been accomplished??
            //(hopefully this will never occur)
            log.info(fieldQRI.getFieldInfo() + ": formatter returned non-string data.");
            criteriaFormula = concatCriteria(criteriaStrs, operStr, false, ta);
        } else {
            if (fieldQRI.getDataClass().equals(Boolean.class)) {
                if (operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.TRUE.getOrdinal()))
                        || operStr.equals(SpQueryField.OperatorType
                                .getOp(SpQueryField.OperatorType.TRUEORNULL.getOrdinal()))) {
                    criteriaFormula = "true";
                } else {
                    criteriaFormula = "false";
                }
                addNullConjunction = operStr.equals(
                        SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.FALSEORNULL.getOrdinal()))
                        || operStr.equals(SpQueryField.OperatorType
                                .getOp(SpQueryField.OperatorType.TRUEORNULL.getOrdinal()));
                operStr = "=";
            } else if (fieldQRI.getDataClass().equals(String.class) && !isNumericCatalogNumber()) {
                criteriaFormula = concatCriteria(criteriaStrs, operStr,
                        !(pickList instanceof PickListTableAdapter), ta);
            } else if (fieldQRI.getDataClass().equals(Calendar.class)
                    || fieldQRI.getDataClass().equals(java.sql.Timestamp.class)) {
                for (int p = 0; p < criteriaStrs.length; p++) {
                    String paramName = "spparam" + paramList.size();
                    try {
                        if (fieldQRI instanceof DateAccessorQRI) {
                            new Integer((String) criteriaStrs[p]);
                        } else {
                            Object arg = dateConverter.convert((String) criteriaStrs[p]);
                            if (fieldQRI.getDataClass().equals(java.sql.Timestamp.class)) {
                                arg = new java.sql.Timestamp(((Calendar) arg).getTimeInMillis());
                            }
                            paramList.add(new Pair<String, Object>(paramName, arg));
                        }
                    } catch (ParseException ex) {
                        throw new ParseException(getLabel() + " - " + String.format(
                                UIRegistry.getResourceString("QB_PARSE_ERROR"), ex.getLocalizedMessage()), -1);
                    }
                    if (p > 0) {
                        if (operatorCBX.getSelectedItem() == SpQueryField.OperatorType.BETWEEN) {
                            criteriaFormula += " and ";
                        } else {
                            criteriaFormula += ", ";
                        }
                    }
                    if (fieldQRI instanceof DateAccessorQRI) {
                        criteriaFormula += (String) criteriaStrs[p];
                    } else {
                        criteriaFormula += ":" + paramName;
                    }
                }
                if (SpQueryField.OperatorType.getOrdForOp(operStr) == SpQueryField.OperatorType.IN
                        .getOrdinal()) {
                    criteriaFormula = "(" + criteriaFormula + ")";
                }
            } else if (Number.class.isAssignableFrom(fieldQRI.getDataClass()) || isNumericCatalogNumber()) {
                Constructor<?> tester;
                try {
                    tester = isNumericCatalogNumber() ? BigInteger.class.getConstructor(String.class)
                            : fieldQRI.getDataClass().getConstructor(String.class);
                    for (int s = 0; s < criteriaStrs.length; s++) {
                        Object critter = criteriaStrs[s];
                        List<String> strs = new ArrayList<String>(2);
                        if (critter instanceof String) {
                            strs.add(critter.toString());
                        } else {
                            //seriesPresent = true;
                            if (!operStr.equals(SpQueryField.OperatorType
                                    .getOp(SpQueryField.OperatorType.IN.getOrdinal()))) {
                                throw new ParseException(getLabel() + " - "
                                        + UIRegistry.getResourceString("QB_INVALID_CRITERIA"), -1);
                            }
                            strs.add(((Pair<String, String>) critter).getFirst());
                            strs.add(((Pair<String, String>) critter).getSecond());
                        }
                        List<String> newStrs = new ArrayList<String>(2);
                        for (String str : strs) {
                            tester.newInstance(str);

                            //remove leading zeroes
                            String newString = str;
                            boolean isZeroes = false;
                            while (newString.startsWith("0")) {
                                newString = newString.substring(1);
                                isZeroes = true;
                            }
                            if (isZeroes && StringUtils.isBlank(newString)) {
                                newString = "0";
                            }
                            newStrs.add(newString);
                        }
                        if (newStrs.size() == 2) {
                            ((Pair<String, String>) criteriaStrs[s]).setFirst(newStrs.get(0));
                            ((Pair<String, String>) criteriaStrs[s]).setSecond(newStrs.get(1));
                        } else {
                            criteriaStrs[s] = newStrs.get(0);
                        }
                    }
                } catch (NoSuchMethodException ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex);
                    // this will never happen. trust me.
                    throw new RuntimeException(ex);
                } catch (InvocationTargetException ex) {
                    if (ex.getTargetException() instanceof NumberFormatException) {
                        String msg = ex.getTargetException().getLocalizedMessage();
                        if (StringUtils.isBlank(msg)) {
                            msg = ex.getTargetException().getClass().getSimpleName();

                        }
                        throw new ParseException(
                                getLabel() + " - "
                                        + String.format(UIRegistry.getResourceString("QB_PARSE_ERROR"), msg),
                                -1);
                    }
                    throw new RuntimeException(ex);
                } catch (IllegalAccessException ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex);
                    throw new RuntimeException(ex);
                } catch (InstantiationException ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex);
                    throw new RuntimeException(ex);
                } catch (NumberFormatException ex) {
                    String msg = ex.getLocalizedMessage();
                    if (StringUtils.isBlank(msg)) {
                        msg = ex.getClass().getSimpleName();
                    }
                    throw new ParseException(getLabel() + " - "
                            + String.format(UIRegistry.getResourceString("QB_PARSE_ERROR"), msg), -1);
                }
                criteriaFormula = concatCriteria(criteriaStrs, operStr, false, ta);
            }
        }
        if (operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.CONTAINS.getOrdinal()))) {
            operStr = "Like";
        }

        if (criteriaFormula.length() > 0 || nullPick || fieldQRI instanceof TreeLevelQRI) {
            if (fieldQRI instanceof TreeLevelQRI) {
                try {
                    return ((TreeLevelQRI) fieldQRI).getNodeNumberCriteria(criteriaFormula, ta, operStr,
                            isNotCheckbox.isSelected());
                } catch (ParseException pe) {
                    throw new ParseException(getLabel() + " - " + String
                            .format(UIRegistry.getResourceString("QB_PARSE_ERROR"), pe.getLocalizedMessage()),
                            -1);

                }
            }

            StringBuilder str = new StringBuilder();

            str.append(isNotCheckbox.isSelected() ? "(NOT " : "");
            if (!operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.IN.getOrdinal()))) {
                str.append(fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()) + " ");
            }
            if (nullPick && "=".equals(operStr)) {
                str.append(" is null ");
            } else if (!operStr
                    .equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.IN.getOrdinal()))) {
                str.append(operStr);
            }
            str.append(" ");
            if (!(nullPick && "=".equals(operStr))) {
                str.append(criteriaFormula);
            }
            if (isNotCheckbox.isSelected()) {
                if (!operStr.equals(
                        SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.EMPTY.getOrdinal()))) {
                    str.append(" or " + fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName())
                            + " is null");
                }
                str.append(")");
            }
            String result = str.toString();
            if (addNullConjunction || (StringUtils.isNotBlank(result) && isEnforcedCkbx != null
                    && isEnforcedCkbx.isSelected() && schemaMapping != null)
                    || (nullPick && !"=".equals(operStr))) {
                //Currently, when the null value is picked with the IN condition, a '' entry is included in the IN list
                //This is not technically correct, but probably will never matter, and possibly produce more desirable 
                //results then the technically correct criteria 
                result = "(" + result + " or "
                        + fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()) + " is null)";
            }
            return result;
        }
    }
    return null;
}

From source file:com.clustercontrol.plugin.impl.SchedulerPlugin.java

private void initDbmsScheduler() throws HinemosUnknown {
    log.debug("initDbmsScheduler() start.");
    Throwable exception = null;/*w  w w.  j a va 2s  .co  m*/

    //???(???Hinemos??)
    String propCron = null;
    String propBaseTime = null;
    propCron = PropertyConstants.hub_transfer_delay_interval.string();
    log.debug("propCron:" + propCron);
    try {
        CronExpression.validateExpression(propCron);
    } catch (ParseException e) {
        log.warn(PropertyConstants.hub_transfer_delay_interval.message_invalid(propCron));
        //?????DB???
        propCron = null;
    }
    propBaseTime = PropertyConstants.hub_transfer_batch_basetime.string();
    log.debug("propBaseTime:" + propBaseTime);

    List<DbmsSchedulerEntity> entityList = null;
    entityList = QueryUtil.getAllDbmsScheduler();

    for (DbmsSchedulerEntity entity : entityList) {
        if (log.isDebugEnabled())
            log.debug("entity:" + entity.getId().getJobId());
        try {
            boolean isMisfire = entity.getMisfireInstr() == Trigger.MISFIRE_INSTRUCTION_DO_NOTHING ? true
                    : false;

            //?
            Serializable[] jdArgs = new Serializable[entity.getJobArgNum()];
            @SuppressWarnings("unchecked")
            Class<? extends Serializable>[] jdArgsType = new Class[entity.getJobArgNum()];

            for (int i = 0; i < entity.getJobArgNum(); i++) {

                String strArg = null;

                switch (i) {
                case 0:
                    strArg = entity.getJobArg00();
                    break;
                case 1:
                    strArg = entity.getJobArg01();
                    break;
                case 2:
                    strArg = entity.getJobArg02();
                    break;
                case 3:
                    strArg = entity.getJobArg03();
                    break;
                case 4:
                    strArg = entity.getJobArg04();
                    break;
                case 5:
                    strArg = entity.getJobArg05();
                    break;
                case 6:
                    strArg = entity.getJobArg06();
                    break;
                case 7:
                    strArg = entity.getJobArg07();
                    break;
                case 8:
                    strArg = entity.getJobArg08();
                    break;
                case 9:
                    strArg = entity.getJobArg09();
                    break;
                case 10:
                    strArg = entity.getJobArg10();
                    break;
                case 11:
                    strArg = entity.getJobArg11();
                    break;
                case 12:
                    strArg = entity.getJobArg12();
                    break;
                case 13:
                    strArg = entity.getJobArg13();
                    break;
                case 14:
                    strArg = entity.getJobArg14();
                    break;
                default:
                    log.debug("arg count ng.");
                }

                if (log.isDebugEnabled())
                    log.debug("strArg[" + i + "]:" + strArg);

                if (strArg != null) {
                    String[] splitArg = strArg.split(":", 2);

                    if (splitArg[0].equals("String")) {
                        jdArgsType[i] = String.class;
                        jdArgs[i] = splitArg[1];
                    } else if (splitArg[0].equals("Boolean")) {
                        jdArgsType[i] = Boolean.class;
                        jdArgs[i] = Boolean.parseBoolean(splitArg[1]);
                    } else if (splitArg[0].equals("Integer")) {
                        jdArgsType[i] = Integer.class;
                        jdArgs[i] = Integer.parseInt(splitArg[1]);
                    } else if (splitArg[0].equals("Long")) {
                        jdArgsType[i] = Long.class;
                        jdArgs[i] = Long.parseLong(splitArg[1]);
                    } else if (splitArg[0].equals("Short")) {
                        jdArgsType[i] = Short.class;
                        jdArgs[i] = Short.parseShort(splitArg[1]);
                    } else if (splitArg[0].equals("Float")) {
                        jdArgsType[i] = Float.class;
                        jdArgs[i] = Float.parseFloat(splitArg[1]);
                    } else if (splitArg[0].equals("Double")) {
                        jdArgsType[i] = Double.class;
                        jdArgs[i] = Double.parseDouble(splitArg[1]);
                    } else if (splitArg[0].equals("nullString")) {
                        jdArgsType[i] = String.class;
                        jdArgs[i] = null;
                    } else {
                        log.debug("not support class");
                    }
                    if (log.isDebugEnabled())
                        log.debug("jdArgs[" + i + "]:" + jdArgs[i]);
                }
            }
            // ??
            JobDetail job = JobBuilder.newJob(ReflectionInvokerJob.class)
                    .withIdentity(entity.getId().getJobId(), entity.getId().getJobGroup()).storeDurably(true) // ??????
                    .usingJobData(ReflectionInvokerJob.KEY_CLASS_NAME, entity.getJobClassName()) // ???????
                    .usingJobData(ReflectionInvokerJob.KEY_METHOD_NAME, entity.getJobMethodName()) // ?????
                    .usingJobData(ReflectionInvokerJob.KEY_RESET_ON_RESTART, isMisfire) // ??trigger()???????
                    .build();

            job.getJobDataMap().put(ReflectionInvokerJob.KEY_ARGS_TYPE, jdArgsType);
            job.getJobDataMap().put(ReflectionInvokerJob.KEY_ARGS, jdArgs);

            // ??trigger?
            Trigger trigger = null;
            if (entity.getTriggerType().equals(SchedulerPlugin.TriggerType.CRON.name())) {
                CronTriggerBuilder triggerBuilder = CronTriggerBuilder.newTrigger()
                        .withIdentity(entity.getId().getJobId(), entity.getId().getJobGroup());
                if (isMisfire) {
                    triggerBuilder.withMisfireHandlingInstructionDoNothing();
                } else {
                    triggerBuilder.withMisfireHandlingInstructionIgnoreMisfires();
                }
                trigger = triggerBuilder.cronSchedule(entity.getCronExpression()).startAt(entity.getStartTime())
                        .endAt(entity.getEndTime()).build();
                ((AbstractTrigger) trigger).setNextFireTime(entity.getNextFireTime());
                ((AbstractTrigger) trigger).setPreviousFireTime(entity.getPrevFireTime());

            } else if (entity.getTriggerType().equals(SchedulerPlugin.TriggerType.SIMPLE.name())) {
                SimpleTriggerBuilder triggerBuilder = SimpleTriggerBuilder.newTrigger()
                        .withIdentity(entity.getId().getJobId(), entity.getId().getJobGroup());
                if (isMisfire) {
                    triggerBuilder.withMisfireHandlingInstructionDoNothing();
                } else {
                    triggerBuilder.withMisfireHandlingInstructionIgnoreMisfires();
                }
                trigger = triggerBuilder.setPeriod(entity.getRepeatInterval()).startAt(entity.getStartTime())
                        .endAt(entity.getEndTime()).build();
                ((AbstractTrigger) trigger).setNextFireTime(entity.getNextFireTime());
                ((AbstractTrigger) trigger).setPreviousFireTime(entity.getPrevFireTime());
            }

            //???(???Hinemos???)
            if (entity.getId().getJobGroup().equals(com.clustercontrol.hub.bean.QuartzConstant.GROUP_NAME)) {
                //???DB?
                TransferInfo ti = null;
                try {
                    ti = com.clustercontrol.hub.util.QueryUtil.getTransferInfo(entity.getId().getJobId(),
                            ObjectPrivilegeMode.MODIFY);
                } catch (LogTransferNotFound e) {
                    log.warn("Not Found TransferInfo:" + entity.getId().getJobId());
                } catch (InvalidRole e) {
                    log.warn("Failed to get TransferInfo for InvalidRole:" + entity.getId().getJobId());
                }
                //????trigger?
                if (ti != null) {
                    if (propCron != null && ti.getTransType() == TransferType.delay) {
                        CronTriggerBuilder triggerBuilder = CronTriggerBuilder.newTrigger()
                                .withIdentity(entity.getId().getJobId(), entity.getId().getJobGroup());
                        if (isMisfire) {
                            triggerBuilder.withMisfireHandlingInstructionDoNothing();
                        } else {
                            triggerBuilder.withMisfireHandlingInstructionIgnoreMisfires();
                        }
                        trigger = triggerBuilder.cronSchedule(propCron)
                                .startAt(HinemosTime.currentTimeMillis() + 15 * 1000).build();
                    } else if (propBaseTime != null && ti.getTransType() == TransferType.batch) {

                        int intervalSec = ti.getInterval() * 60 * 60;
                        long baseTime = com.clustercontrol.hub.factory.ModifySchedule.getBaseTime(propBaseTime,
                                intervalSec);
                        log.debug("baseTime:" + baseTime);
                        SimpleTriggerBuilder triggerBuilder = SimpleTriggerBuilder.newTrigger()
                                .withIdentity(entity.getId().getJobId(), entity.getId().getJobGroup());
                        if (isMisfire) {
                            triggerBuilder.withMisfireHandlingInstructionDoNothing();
                        } else {
                            triggerBuilder.withMisfireHandlingInstructionIgnoreMisfires();
                        }
                        trigger = triggerBuilder.setPeriod(intervalSec * 1000).startAt(baseTime).build();
                    }
                }
                //?DB
                try {
                    ModifyDbmsScheduler dbms = new ModifyDbmsScheduler();
                    dbms.modifyDbmsScheduler(job, trigger);
                    trigger.computeFirstFireTime(HinemosTime.currentTimeMillis());
                    dbms.modifyDbmsSchedulerInternal(job, trigger, TriggerState.SCHEDULED.name());
                } catch (Exception e) {
                    log.warn("hub setting init err. entity : jobId = " + entity.getId().getJobId() + ", "
                            + entity.getId().getJobGroup() + ", " + e.getClass().getSimpleName() + ", "
                            + e.getMessage());
                    exception = e;
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("getNextFireTime=" + trigger.getNextFireTime() + ", getPreviousFireTime="
                        + trigger.getPreviousFireTime());
            }
            // ?
            synchronized (_schedulerLock) {
                if (log.isDebugEnabled())
                    log.debug("scheduleJob() name=" + entity.getId().getJobId() + ", group="
                            + entity.getId().getJobGroup());
                // DB???????RAM??/????
                _scheduler.get(SchedulerPlugin.SchedulerType.DBMS).initDbmsScheduleJob(job, trigger,
                        entity.getTriggerState());
            }
        } catch (RuntimeException e) {
            log.warn("initDbmsScheduler() entity : jobId = " + entity.getId().getJobId() + ", "
                    + entity.getId().getJobGroup() + ", " + e.getClass().getSimpleName() + ", "
                    + e.getMessage());
            // ??????throw????
            exception = e;
        }
    }

    if (exception != null) {
        throw new HinemosUnknown("failed dbms scheduler:", exception);
    }
    log.debug("initDbmsScheduler() end.");
}