Example usage for java.text ParseException getMessage

List of usage examples for java.text ParseException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java

/**
 * create a subjob for each day in the date range, using first parameter as a template.
 * Then transfer all the rinex files for each subjob. 
 * @param strDateFrom//from  w  w  w. java  2s  . co m
 * @param strDateTo
 * @param param
 * @return array of strings
 */
private String[] createSubjobs(String strDateFrom, String strDateTo, String param, HttpServletRequest request,
        List<GeodesyGridInputFile> gpsFiles) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<String> paramList = new ArrayList<String>();
    // Save in session to use it when submitting job
    String jobInputDir = (String) request.getSession().getAttribute("jobInputDir");

    //Use the first parameter from GUI as template for generating param for each day in the date range
    String paramTemp = param.substring(param.indexOf("-expt", 0), param.length());

    try {
        Date dateFrom = df.parse(strDateFrom);
        Date dateTo = df.parse(strDateTo);

        Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(dateFrom);

        Calendar calTo = Calendar.getInstance();
        calTo.setTime(dateTo);

        //String gpsFiles = (String)request.getSession().getAttribute("gridInputFiles");   
        //List<String> urlsList = GeodesyUtil.getSelectedGPSFiles(gpsFiles);

        //while dateFrom is less than or equal to dateTo
        int jobCount = 0;
        while ((calFrom.compareTo(calTo)) <= 0) {
            //TO-DO check if this subJob has renix files available
            int year = calFrom.get(Calendar.YEAR);
            int doy = calFrom.get(Calendar.DAY_OF_YEAR);
            String strParam = "-d " + year + " " + doy + " " + paramTemp;
            paramList.add(strParam);

            String[] rinexOfDay = getRinexFilesOfDate(calFrom, gpsFiles);
            if (rinexOfDay.length > 0) {
                //First create subJob/rinex/ directories path for this subJob
                //Then urlcopy relevent rinex files for this sub job
                String subJobId = "subJob_" + jobCount;
                String subJobDir = jobInputDir + subJobId + File.separator;
                if (createGridDir(request, subJobDir)) {
                    String rinexSubJobDir = subJobDir + GridSubmitController.RINEX_DIR + File.separator;
                    if (createGridDir(request, rinexSubJobDir)) {
                        // Full URL
                        // e.g. "gsiftp://pbstore.ivec.org:2811//pbstore/au01/grid-auscope/Abdi.Jama@csiro.au-20091103_163322/"
                        //       +"rinex/" + filename
                        String toURL = gridAccess.getGridFtpServer() + File.separator + rinexSubJobDir;
                        urlCopy(rinexOfDay, request, toURL);

                        Hashtable subJobStageInDir = (Hashtable) request.getSession()
                                .getAttribute("subJobStageInDir");

                        if (subJobStageInDir == null)
                            subJobStageInDir = new Hashtable();

                        if (!subJobStageInDir.containsKey(subJobId)) {
                            String gridSubjobDir = gridAccess.getGridFtpServer() + subJobDir;
                            subJobStageInDir.put(subJobId, gridSubjobDir);
                            request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                            logger.info("Added gridStageInDir: " + gridSubjobDir);
                        }
                    }
                    /*Hashtable subJobStageInDir = (Hashtable) request.getSession().getAttribute("subJobStageInDir");
                            
                    if(subJobStageInDir == null)
                       subJobStageInDir = new Hashtable();
                            
                    if(!subJobStageInDir.containsKey(subJobId)){
                       String gridSubjobDir = gridAccess.getGridFtpServer()+subJobDir;
                       subJobStageInDir.put(subJobId, gridSubjobDir);
                       request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                       logger.info("Added gridStageInDir: "+gridSubjobDir);
                    }*/
                }
            } else {
                logger.info("No rinex files found for this day: " + year + "-" + doy);
            }

            calFrom.add(Calendar.DATE, 1);
            jobCount++;
            logger.debug("Added param: " + strParam);
        }
    } catch (ParseException e) {
        //do we need to pass this to the gui
        logger.error("Error casting date: " + e.getMessage());
    }
    String[] paramArray = new String[paramList.size()];
    paramArray = paramList.toArray(paramArray);
    return paramArray;
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

/**
 * Populate koopman fragment from local member vars
 *///from  ww  w .  j a v  a 2  s .co m
private void populateKoopmanFragment() {
    if (mKoopmanFragmentReady) {

        // for an existing dagvergunning hide the koopman discovery options
        if (mId > 0) {
            Utility.collapseView(mKoopmanFragment.mErkenningsnummerLayout, true);
            Utility.collapseView(mKoopmanFragment.mSollicitatienummerLayout, true);
            Utility.collapseView(mKoopmanFragment.mScanbuttonsLayout, true);
        } else {
            Utility.collapseView(mKoopmanFragment.mErkenningsnummerLayout, false);
            Utility.collapseView(mKoopmanFragment.mSollicitatienummerLayout, false);
            Utility.collapseView(mKoopmanFragment.mScanbuttonsLayout, false);
        }

        // set the vervanger details and toggle aanwezig spinner
        if (mVervangerId > 0) {
            mKoopmanFragment.mVervangerId = mVervangerId;
            mKoopmanFragment.mVervangerErkenningsnummer = mVervangerErkenningsnummer;
            mKoopmanAanwezig = getString(R.string.item_vervanger_met_toestemming_aanwezig);
            mKoopmanFragment.mAanwezigSelectedValue = mKoopmanAanwezig;
        } else {
            mKoopmanFragment.mVervangerId = -1;
            mKoopmanFragment.mVervangerErkenningsnummer = null;
        }

        // set the koopman details
        if (mKoopmanId > 0) {
            mKoopmanFragment.setKoopman(mKoopmanId, mId);
        }

        // dagvergunning registratie tijd
        if (mRegistratieDatumtijd != null) {
            try {
                Date registratieDate = new SimpleDateFormat(getString(R.string.date_format_datumtijd),
                        Locale.getDefault()).parse(mRegistratieDatumtijd);
                SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_tijd));
                String registratieTijd = sdf.format(registratieDate);
                mKoopmanFragment.mRegistratieDatumtijdText.setText(registratieTijd);
            } catch (java.text.ParseException e) {
                Utility.log(getContext(), LOG_TAG, "Format registratie tijd failed: " + e.getMessage());
            }
        } else {
            mKoopmanFragment.mRegistratieDatumtijdText.setText("");
        }

        // dagvergunning notitie
        if (mNotitie != null && !mNotitie.equals("")) {
            mKoopmanFragment.mNotitieText.setText(getString(R.string.label_notitie) + ": " + mNotitie);
            Utility.collapseView(mKoopmanFragment.mNotitieText, false);
        } else {
            Utility.collapseView(mKoopmanFragment.mNotitieText, true);
        }

        // dagvergunning totale lengte
        if (mTotaleLengte != -1) {
            mKoopmanFragment.mTotaleLengte.setText(mTotaleLengte + " " + getString(R.string.length_meter));
        }

        // registratie account naam
        if (mRegistratieAccountNaam != null) {
            mKoopmanFragment.mAccountNaam.setText(mRegistratieAccountNaam);
        } else {
            mKoopmanFragment.mAccountNaam.setText("");
        }

        // koopman aanwezig status
        if (mKoopmanAanwezig != null) {
            mKoopmanFragment.setAanwezig(mKoopmanAanwezig);
        }
    }
}

From source file:uk.ac.ebi.intact.editor.controller.curate.publication.PublicationController.java

public void publicationYearChanged(ValueChangeEvent evt) {
    setUnsavedChanges(true);//from  w  w  w. j  a v a 2 s.  c o m
    Short newValue = (Short) evt.getNewValue();

    if (newValue != null && newValue > 0) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        try {
            this.publication.setPublicationDate(formatter.parse(Short.toString(newValue)));
            this.year = newValue;
            setExperimentAnnotation(Annotation.PUBLICATION_YEAR, Annotation.PUBLICATION_YEAR_MI,
                    Short.toString(newValue));
        } catch (ParseException e) {
            this.year = null;
            addErrorMessage("The publication year is not a valid year " + newValue,
                    e.getCause() + ": " + e.getMessage());
        }
    } else {
        this.publication.setPublicationDate(null);
        this.year = null;
    }
}

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 a  v a2  s  .c o m
        // 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.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

/**
 * Returns the license details like license expiry date, CPU license count, etc.
 * /* www .ja  v a 2  s  .co  m*/
 * @return {@link Map}<{@link String}, {@link String}>: license details
 */
@Override
public Map<String, String> getLicenseDetails() {
    String licenseInfoString = null;
    Map<String, String> licenseDetailMap = null;

    LOGGER.debug("License details: ", licenseInfoString);

    final String[] licenseDetails = EphesoftStringUtil.splitString(licenseInfoString, CoreCommonConstant.COMMA);

    if (null != licenseDetails) {
        int indexOfFirstColon = 0;
        String licensePropertyName = null;
        String licensePropertyValue = null;
        licenseDetailMap = new LinkedHashMap<String, String>(licenseDetails.length);
        for (final String licenseDetail : licenseDetails) {
            indexOfFirstColon = licenseDetail.indexOf(CoreCommonConstant.COLON);
            if ((indexOfFirstColon > 0) && (indexOfFirstColon < licenseDetail.length())) {
                licensePropertyName = licenseDetail.substring(0, indexOfFirstColon - 1);
                licensePropertyValue = licenseDetail.substring(indexOfFirstColon + CoreCommonConstant.TWO);

                LOGGER.debug("License Property Name: ", licensePropertyName, "and License Property Value: ",
                        licensePropertyValue);

                if (CoreCommonConstant.EXPIRY_DATE_LICENSE_PROPERTY_NAME
                        .equalsIgnoreCase(licensePropertyName)) {
                    final DateFormat formatter = new SimpleDateFormat(CoreCommonConstant.EXTENDED_DATE_FORMAT);
                    formatter.setTimeZone(TimeZone.getTimeZone(CoreCommonConstant.GMT));
                    try {
                        final Date date = formatter.parse(licensePropertyValue);
                        licensePropertyValue = date.toGMTString();
                    } catch (final ParseException parseException) {
                        LOGGER.error(parseException, "Error while parsing the date",
                                parseException.getMessage());
                    }
                }

                if (CoreCommonConstants.ON.equals(licensePropertyValue)
                        || CoreCommonConstants.OFF.equals(licensePropertyValue)) {
                    licensePropertyValue = licensePropertyValue.toUpperCase();
                }

                if (CoreCommonConstant.MUTLISERVER_SWITCH_LICENSE_PROPERTY_NAME
                        .equalsIgnoreCase(licensePropertyName)) {
                    licensePropertyName = CoreCommonConstant.MUTLISERVER_SWITCH;
                }

                // Fix for Client Ticket #3340 changed name of advance reporting switch label.
                if (CoreCommonConstant.ADVANCE_REPORTING_SWITCH_PROPERTY_NAME
                        .equalsIgnoreCase(licensePropertyName)) {
                    licensePropertyName = CoreCommonConstant.ADVANCED_REPORTING_SWITCH;
                }

                if (CoreCommonConstant.EXPIRY_DATE_MESSAGE_LICENSE_PROPERTY_NAME
                        .equalsIgnoreCase(licensePropertyName)) {
                    licensePropertyName = CoreCommonConstant.LICENSE_EXPIRATION_DISPLAY_MESSGAE;
                    final String[] licensePropertyTokens = EphesoftStringUtil.splitString(licensePropertyValue,
                            CoreCommonConstant.SPACE);
                    if (null != licensePropertyTokens) {
                        licensePropertyValue = EphesoftStringUtil.concatenate(licensePropertyTokens[0],
                                CoreCommonConstant.SPACE, CoreCommonConstant.DAYS);
                    }

                }

                licenseDetailMap.put(licensePropertyName, licensePropertyValue);
            }
        }

        // Removing license failOver value into License detail UI
        // ClusterPropertyService clusterPropertyService =
        // this.getSingleBeanOfType(ClusterPropertyService.class);
        // licensePropertyName =
        // SystemConfigConstants.LICENSE_SERVER_FO_HEADER;
        //
        // ClusterProperty failOverProperty = clusterPropertyService
        // .getClusterPropertyValue(ClusterPropertyType.LICENSE_FAILOVER_MECHANISM);
        // if (null != failOverProperty) {
        // String switchStatus = failOverProperty.getPropertyValue();
        // if (!EphesoftStringUtil.isNullOrEmpty(switchStatus)) {
        // if (CoreCommonConstants.ON.equalsIgnoreCase(switchStatus)) {
        // licensePropertyValue = CoreCommonConstants.ON.toUpperCase();
        // } else {
        // licensePropertyValue = CoreCommonConstants.OFF.toUpperCase();
        // }
        // }
        // }
        // licenseDetailMap.put(licensePropertyName, licensePropertyValue);
    }
    return licenseDetailMap;
}

From source file:org.egov.egf.web.actions.payment.PaymentAction.java

@ValidationErrorPage(value = LIST)
@SkipValidation//from ww  w.  j a  va2 s . c  om
public String modifyAdvancePayment() {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting modifyAdvancePayment...");
    paymentheader = (Paymentheader) persistenceService.find(" from Paymentheader where id=? ",
            paymentheader.getId());
    addDropdownData("bankaccountList",
            persistenceService.findAllBy(
                    " from Bankaccount where bankbranch.id=? and isactive=true and fund.id=?",
                    paymentheader.getBankaccount().getBankbranch().getId(),
                    paymentheader.getBankaccount().getFund().getId()));
    loadbankBranch(paymentheader.getVoucherheader().getFundId());
    advanceRequisitionList.addAll(paymentActionHelper.getAdvanceRequisitionDetails(paymentheader));
    final String vNumGenMode = voucherTypeForULB.readVoucherTypes("Payment");
    if (!"Auto".equalsIgnoreCase(vNumGenMode)) {
        voucherNumberPrefix = paymentheader.getVoucherheader().getVoucherNumber().substring(0,
                Integer.valueOf(FinancialConstants.VOUCHERNO_TYPE_LENGTH));
        voucherNumberSuffix = paymentheader.getVoucherheader().getVoucherNumber()
                .substring(Integer.valueOf(FinancialConstants.VOUCHERNO_TYPE_LENGTH,
                        paymentheader.getVoucherheader().getVoucherNumber().length()));
    }
    try {
        balance = paymentService.getAccountBalance(paymentheader.getBankaccount().getId().toString(),
                formatter.format(new Date()), paymentheader.getPaymentAmount(), paymentheader.getId(),
                paymentheader.getBankaccount().getChartofaccounts().getId());
    } catch (final ParseException e) {
        LOGGER.error("Error" + e.getMessage(), e);
        throw new ValidationException(Arrays
                .asList(new ValidationError("Error While formatting date", "Error While formatting date")));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed modifyAdvancePayment...");
    return "advancePaymentModify";
}

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

/**
 * Only works if we have path to GIT/* w  w  w . j av a2 s  .c o m*/
 */
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:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java

private Set<OrganizacionEvento> buscarEventos(Element eventsEl, Organizacion organizacion) {
    if (eventsEl == null)
        return null;

    Set<OrganizacionEvento> ret = new HashSet<OrganizacionEvento>();

    NodeList nodeLst = eventsEl.getElementsByTagName("event");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elEvento = (Element) fstNode;

            String localization = XmlParserUtil.getStringNodeValue(elEvento, "localization");
            String title = XmlParserUtil.getStringNodeValue(elEvento, "title");
            String description = XmlParserUtil.getStringNodeValue(elEvento, "description");
            String date = XmlParserUtil.getStringNodeValue(elEvento, "date");

            Date fecha = null;/*from w w  w .  j  a v a2 s.c  o m*/
            try {
                fecha = formatter.parse(date);
            } catch (ParseException e) {
            }

            Evento evento = null;

            if (organizacion.getEventos() != null) {
                for (OrganizacionEvento oe : organizacion.getEventos()) {
                    Evento e = oe.getEvento();
                    if (e.getTitulo().equals(title)) {
                        evento = e;
                        break;
                    }
                }
            }
            if (evento == null) {
                evento = new Evento();

                evento.setLocalizacion(localization);
                evento.setTitulo(title);
                evento.setDescripcion(description);
                evento.setFecha(fecha);
                try {
                    organizacionService.saveEvento(evento);

                    OrganizacionEvento eventoOrg = new OrganizacionEvento();
                    eventoOrg.setEvento(evento);
                    eventoOrg.setOrganizacion(organizacion);
                    ret.add(eventoOrg);
                } catch (ServiceException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
    return ret;
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

/**
 * Populate overzicht fragment from local member vars
 */// w w  w  .  j  a va2 s .c om
private void populateOverzichtFragment() {
    if (mOverzichtFragmentReady) {

        // TODO: show the changes in case we are editing an existing dagvergunning

        // koopman
        if (mKoopmanId > 0) {
            mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.VISIBLE);
            mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.GONE);

            // koopman details
            mOverzichtFragment.setKoopman(mKoopmanId);

            // dagvergunning registratie tijd
            if (mRegistratieDatumtijd != null) {
                try {
                    Date registratieDate = new SimpleDateFormat(getString(R.string.date_format_datumtijd),
                            Locale.getDefault()).parse(mRegistratieDatumtijd);
                    SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_tijd));
                    String registratieTijd = sdf.format(registratieDate);
                    mOverzichtFragment.mRegistratieDatumtijdText.setText(registratieTijd);
                } catch (java.text.ParseException e) {
                    Utility.log(getContext(), LOG_TAG, "Format registratie tijd failed: " + e.getMessage());
                }
            } else {
                mOverzichtFragment.mRegistratieDatumtijdText.setText("");
            }

            // dagvergunning notitie
            if (mNotitie != null && !mNotitie.equals("")) {
                mOverzichtFragment.mNotitieText.setText(getString(R.string.label_notitie) + ": " + mNotitie);
                Utility.collapseView(mOverzichtFragment.mNotitieText, false);
            } else {
                Utility.collapseView(mOverzichtFragment.mNotitieText, true);
            }

            // dagvergunning totale lengte
            if (mTotaleLengte != -1) {
                mOverzichtFragment.mTotaleLengte
                        .setText(mTotaleLengte + " " + getString(R.string.length_meter));
            }

            // registratie account naam
            if (mRegistratieAccountNaam != null) {
                mOverzichtFragment.mAccountNaam.setText(mRegistratieAccountNaam);
            } else {
                mOverzichtFragment.mAccountNaam.setText("");
            }

            // koopman aanwezig status
            if (mKoopmanAanwezig != null) {

                // get the corresponding aanwezig title from the resource array based on the aanwezig key
                String[] aanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key);
                String[] aanwezigTitles = getResources().getStringArray(R.array.array_aanwezig_title);
                String aanwezigTitle = "";
                for (int i = 0; i < aanwezigKeys.length; i++) {
                    if (aanwezigKeys[i].equals(mKoopmanAanwezig)) {
                        aanwezigTitle = aanwezigTitles[i];
                    }
                }
                mOverzichtFragment.mAanwezigText.setText(aanwezigTitle);
            }

            // vervanger
            if (mVervangerId > 0) {

                // hide the aanwezig status and populate and show the vervanger details
                mOverzichtFragment.mAanwezigText.setVisibility(View.GONE);
                mOverzichtFragment.mVervangerDetail.setVisibility(View.VISIBLE);
                mOverzichtFragment.setVervanger(mVervangerId);
            } else {

                // show the aanwezig status and hide the vervanger details
                mOverzichtFragment.mAanwezigText.setVisibility(View.VISIBLE);
                mOverzichtFragment.mVervangerDetail.setVisibility(View.GONE);
            }
        } else {
            mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.VISIBLE);
            mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.GONE);
        }

        // product
        if (mErkenningsnummer != null && isProductSelected()) {

            // show progress bar
            mProgressbar.setVisibility(View.VISIBLE);

            // disable save function until we have a response from the api for a concept factuur
            mConceptFactuurDownloaded = false;

            // post the dagvergunning details to the api and retrieve a concept 'factuur'
            ApiPostDagvergunningConcept postDagvergunningConcept = new ApiPostDagvergunningConcept(
                    getContext());
            postDagvergunningConcept.setPayload(dagvergunningToJson());
            postDagvergunningConcept.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Response<JsonObject> response) {

                    // hide progress bar
                    mProgressbar.setVisibility(View.GONE);

                    if (response.isSuccess() && response.body() != null) {
                        mOverzichtFragment.mProductenLinearLayout.setVisibility(View.VISIBLE);
                        mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.GONE);

                        // enable save function and give wizard next button background enabled color
                        mConceptFactuurDownloaded = true;
                        mWizardNextButton
                                .setBackgroundColor(ContextCompat.getColor(getContext(), R.color.accent));

                        // from the response, populate the product section of the overzicht fragment
                        View overzichtView = mOverzichtFragment.getView();
                        if (overzichtView != null) {

                            // find placeholder table layout view
                            TableLayout placeholderLayout = (TableLayout) overzichtView
                                    .findViewById(R.id.producten_placeholder);
                            if (placeholderLayout != null) {
                                placeholderLayout.removeAllViews();
                                LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                                // get the producten array
                                JsonArray producten = response.body().getAsJsonArray(getString(
                                        R.string.makkelijkemarkt_api_dagvergunning_concept_producten));

                                if (producten != null) {
                                    int rowCount = 0;

                                    // table header
                                    View headerLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView btwHeaderText = (TextView) headerLayout
                                            .findViewById(R.id.btw_totaal);
                                    btwHeaderText.setText("BTW");
                                    TextView exclusiefHeaderText = (TextView) headerLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    exclusiefHeaderText.setText("Ex. BTW");
                                    placeholderLayout.addView(headerLayout, rowCount++);

                                    for (int i = 0; i < producten.size(); i++) {
                                        JsonObject product = producten.get(i).getAsJsonObject();

                                        // get the product item layout
                                        View childLayout = layoutInflater
                                                .inflate(R.layout.dagvergunning_overzicht_product_item, null);

                                        // aantal
                                        if (product.get("aantal") != null
                                                && !product.get("aantal").isJsonNull()) {
                                            TextView aantalText = (TextView) childLayout
                                                    .findViewById(R.id.product_aantal);
                                            aantalText.setText(product.get("aantal").getAsInt() + " x ");
                                        }

                                        // naam
                                        if (product.get("naam") != null && !product.get("naam").isJsonNull()) {
                                            TextView naamText = (TextView) childLayout
                                                    .findViewById(R.id.product_naam);
                                            naamText.setText(
                                                    Utility.capitalize(product.get("naam").getAsString()));
                                        }

                                        // btw %
                                        if (product.get("btw_percentage") != null
                                                && !product.get("btw_percentage").isJsonNull()) {
                                            long btwPercentage = Math.round(Double
                                                    .parseDouble(product.get("btw_percentage").getAsString()));
                                            if (btwPercentage != 0) {
                                                TextView btwPercentageText = (TextView) childLayout
                                                        .findViewById(R.id.btw_percentage);
                                                btwPercentageText.setText(btwPercentage + "%");
                                            }
                                        }

                                        // btw totaal
                                        if (product.get("btw_totaal") != null
                                                && !product.get("btw_totaal").isJsonNull()) {
                                            double btwTotaalProduct = Double
                                                    .parseDouble(product.get("btw_totaal").getAsString());
                                            TextView btwTotaalText = (TextView) childLayout
                                                    .findViewById(R.id.btw_totaal);
                                            if (Math.round(btwTotaalProduct) != 0) {
                                                btwTotaalText
                                                        .setText(String.format(" %.2f", btwTotaalProduct));
                                            } else {
                                                btwTotaalText.setText("-");
                                            }
                                        }

                                        // bedrag totaal
                                        if (product.get("totaal") != null
                                                && !product.get("totaal").isJsonNull()) {
                                            double bedragTotaal = Double
                                                    .parseDouble(product.get("totaal").getAsString());
                                            TextView bedragTotaalText = (TextView) childLayout
                                                    .findViewById(R.id.bedrag_totaal);
                                            bedragTotaalText.setText(String.format(" %.2f", bedragTotaal));
                                        }

                                        // add child view
                                        placeholderLayout.addView(childLayout, rowCount++);
                                    }

                                    // exclusief
                                    double exclusief = 0;
                                    if (response.body().get("exclusief") != null
                                            && !response.body().get("exclusief").isJsonNull()) {
                                        exclusief = Double
                                                .parseDouble(response.body().get("exclusief").getAsString());
                                    }

                                    // totaal
                                    double totaal = 0;
                                    if (response.body().get("totaal") != null
                                            && !response.body().get("totaal").isJsonNull()) {
                                        totaal = response.body().get("totaal").getAsDouble();
                                    }

                                    // totaal btw en ex. btw
                                    View totaalLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView naamText = (TextView) totaalLayout.findViewById(R.id.product_naam);
                                    naamText.setText("Totaal");
                                    TextView btwTotaalText = (TextView) totaalLayout
                                            .findViewById(R.id.btw_totaal);
                                    if (Math.round(totaal - exclusief) != 0) {
                                        btwTotaalText.setText(String.format(" %.2f", (totaal - exclusief)));
                                    }
                                    TextView exclusiefText = (TextView) totaalLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    exclusiefText.setText(String.format(" %.2f", exclusief));
                                    placeholderLayout.addView(totaalLayout, rowCount++);

                                    // separator
                                    View emptyLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    placeholderLayout.addView(emptyLayout, rowCount++);

                                    // totaal inc. btw
                                    View totaalIncLayout = layoutInflater
                                            .inflate(R.layout.dagvergunning_overzicht_product_item, null);
                                    TextView totaalNaamText = (TextView) totaalIncLayout
                                            .findViewById(R.id.product_naam);
                                    totaalNaamText.setText("Totaal inc. BTW");
                                    TextView totaalIncText = (TextView) totaalIncLayout
                                            .findViewById(R.id.bedrag_totaal);
                                    totaalIncText.setText(String.format(" %.2f", totaal));
                                    placeholderLayout.addView(totaalIncLayout, rowCount);
                                }
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    mProgressbar.setVisibility(View.GONE);
                }
            });
        } else {
            mOverzichtFragment.mProductenLinearLayout.setVisibility(View.GONE);

            if (mKoopmanId > 0) {
                mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.VISIBLE);
            }
        }
    }
}

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

/**
 * Only works if we have path to GIT//from  w w w  . ja v  a 2s .  c o 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;
}