Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

In this page you can find the example usage for java.util Date compareTo.

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:com.biosis.biosislite.vistas.AsignarPermiso.java

private boolean erroresFormulario() {
    int errores = 0;
    Date fechaInicio = dcFechaInicio.getDate();

    String mensaje = "";
    if (integrantes.isEmpty()) {
        errores++;//from  www  .j a v a  2  s  .  c  o m
        mensaje += ">Debe seleccionar uno o mas empleados\n";
    }

    if (dcFechaInicio.getDate() == null || dcFechaFin.getDate() == null) {

        if (!radHora.isSelected()) {
            errores++;
            mensaje += "Una o ms fechas ingresadas incorrectamente \n";
        } else if (radFecha.isSelected()) {
            errores++;
            mensaje += "Una o ms fechas ingresadas incorrectamente \n";
        }

    } else {
        if (radFecha.isSelected()) {
            Date fechaFin = dcFechaFin.getDate();
            if (fechaInicio.compareTo(fechaFin) > 0) {
                errores++;
                mensaje += ">La fecha de inicio debe ser menor que la fecha de fin\n";
            }
            //Traemos los dnis de los empleados
            Permiso paraComprobar = this.controlador.getSeleccionado();
            //List<String> dnis = new ArrayList<>();
            for (AsignacionPermiso asignacion : paraComprobar.getAsignacionPermisoList()) {
                //dnis.add(asignacion.getEmpleado());
                System.out.println(asignacion.getEmpleado());
                //                List<AsignacionPermiso> lista = ac.buscarXFechaDni(asignacion.getEmpleado(), fechaInicio);
                int conteoPorFecha = ac.contarXEmpleadoEntreFechaPorFecha(empleadoSeleccionado, fechaInicio,
                        fechaFin);
                if (conteoPorFecha == 0) {

                } else if (accion != Controlador.MODIFICAR) {
                    errores++;
                    mensaje += "El empleado " + asignacion.getEmpleado()
                            + " tiene conflicto con un permiso aadido anteriormente \n Ingrese otro rango de fechas \n";
                    break;
                }
            }
        }
    }

    //Traemos los permisos por dni
    if (radHora.isSelected()) {
        Date horaInicio = (Date) spHoraInicio.getValue();
        Date horaFin = (Date) spHoraFin.getValue();
        if (horaInicio.compareTo(horaFin) > 0) {
            errores++;
            mensaje += ">La hora de inicio debe ser menor que la hora de fin \n";
        }
        Permiso paraComprobar = this.controlador.getSeleccionado();
        for (AsignacionPermiso asignacion : paraComprobar.getAsignacionPermisoList()) {
            List<AsignacionPermiso> lista = ac.buscarXHora(asignacion.getEmpleado(), fechaInicio);

            Long conteoPorHora = lista.stream()
                    .filter(perm -> (horaInicio.compareTo(perm.getPermiso().getHoraInicio()) <= 0
                            && horaFin.compareTo(perm.getPermiso().getHoraInicio()) >= 0)
                            || (perm.getPermiso().getHoraInicio().compareTo(horaInicio) <= 0
                                    && perm.getPermiso().getHoraFin().compareTo(horaInicio) >= 0))
                    .count();
            if (conteoPorHora.intValue() == 0) {

            } else {
                errores++;
                mensaje += ">El empleado " + asignacion.getEmpleado()
                        + " tiene conflicto con un permiso aadido anteriormente \n Ingrese otro rango de horas\n";
                break;
            }
        }
    }
    if (errores > 0) {
        JOptionPane.showMessageDialog(this, "Se ha(n) encontrado el(los) siguiente(s) error(es):\n" + mensaje,
                "Mensaje del sistema", JOptionPane.ERROR_MESSAGE);
    }
    return errores != 0;
}

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testTailLogMultipleDirs() throws Exception {
    File testDataDir1 = new File("target", UUID.randomUUID().toString());
    File testDataDir2 = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir1.mkdirs());
    Assert.assertTrue(testDataDir2.mkdirs());
    Files.write(new File(testDataDir1, "log1.txt").toPath(), Arrays.asList("Hello"), UTF8);
    Files.write(new File(testDataDir2, "log2.txt").toPath(), Arrays.asList("Hola"), UTF8);

    FileInfo fileInfo1 = new FileInfo();
    fileInfo1.tag = "tag1";
    fileInfo1.fileFullPath = testDataDir1.getAbsolutePath() + "/log1.txt";
    fileInfo1.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo1.firstFile = "";
    fileInfo1.patternForToken = "";
    FileInfo fileInfo2 = new FileInfo();
    fileInfo2.tag = "";
    fileInfo2.fileFullPath = testDataDir2.getAbsolutePath() + "/log2.txt";
    fileInfo2.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo2.firstFile = "";
    fileInfo2.patternForToken = "";

    FileTailConfigBean conf = new FileTailConfigBean();
    conf.dataFormat = DataFormat.TEXT;/*w w w .  j av a2s . co  m*/
    conf.multiLineMainPattern = "";
    conf.batchSize = 25;
    conf.maxWaitTimeSecs = 1;
    conf.fileInfos = Arrays.asList(fileInfo1, fileInfo2);
    conf.postProcessing = PostProcessingOptions.NONE;
    conf.dataFormatConfig.textMaxLineLen = 1024;

    FileTailSource source = new FileTailSource(conf, SCAN_INTERVAL);
    SourceRunner runner = new SourceRunner.Builder(FileTailDSource.class, source).addOutputLane("lane")
            .addOutputLane("metadata").build();
    runner.runInit();
    try {
        Date now = new Date();
        Thread.sleep(10);
        StageRunner.Output output = runner.runProduce(null, 1000);
        Assert.assertEquals(2, output.getRecords().get("lane").size());
        Record record = output.getRecords().get("lane").get(0);
        Assert.assertEquals("Hello", record.get("/text").getValueAsString());
        Assert.assertEquals("tag1", record.getHeader().getAttribute("tag"));
        Assert.assertEquals(fileInfo1.fileFullPath, record.getHeader().getAttribute("file"));
        record = output.getRecords().get("lane").get(1);
        Assert.assertEquals("Hola", record.get("/text").getValueAsString());
        Assert.assertNull(record.getHeader().getAttribute("tag"));
        Assert.assertEquals(fileInfo2.fileFullPath, record.getHeader().getAttribute("file"));

        Assert.assertEquals(2, output.getRecords().get("metadata").size());
        Record metadata = output.getRecords().get("metadata").get(0);
        Assert.assertEquals(new File(fileInfo1.fileFullPath).getAbsolutePath(),
                metadata.get("/fileName").getValueAsString());
        Assert.assertEquals("START", metadata.get("/event").getValueAsString());
        Assert.assertTrue(now.compareTo(metadata.get("/time").getValueAsDate()) < 0);
        Assert.assertTrue(metadata.has("/inode"));
        metadata = output.getRecords().get("metadata").get(1);
        Assert.assertEquals(new File(fileInfo2.fileFullPath).getAbsolutePath(),
                metadata.get("/fileName").getValueAsString());
        Assert.assertEquals("START", metadata.get("/event").getValueAsString());
        Assert.assertTrue(now.compareTo(metadata.get("/time").getValueAsDate()) < 0);
        Assert.assertTrue(metadata.has("/inode"));
    } finally {
        runner.runDestroy();
    }
}

From source file:com.virtusa.akura.reporting.validator.StudentWiseSwipeInOutAttendanceValidator.java

/**
 * Validates the user input for criteria.
 *
 * @param object - Populated object of StudentWiseAttendanceTemplate to validate
 * @param errors - contain errors related to fields.
 * @throws AkuraAppException - throws when exception occurs.
 *///from w  w w. j  av a  2 s.  com
public void validate(Object object, Errors errors) throws AkuraAppException {

    Date dateFrom = null;

    StudentWiseSwipInOutTemplate studentWiseSwipInOutTemplate = (StudentWiseSwipInOutTemplate) object;

    if (studentWiseSwipInOutTemplate.getDateFrom().equals(STRING_NULL)
            || studentWiseSwipInOutTemplate.getDateTo().equals(STRING_NULL)) {
        errors.rejectValue(VAR_DATE_TO, ERROR_MSG_REF_UI_MANDATORY_FIELD_REQUIRED);
    } else {
        Pattern datePattern = Pattern.compile(DATE_PATTERN);

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD);
        if (!studentWiseSwipInOutTemplate.getDateFrom().equals(STRING_NULL)) {
            Matcher dateFromPatternMatcher = datePattern.matcher(studentWiseSwipInOutTemplate.getDateFrom());
            if (!dateFromPatternMatcher.find()) {
                errors.rejectValue(VAR_DATE_FROM, ERROR_INVALID_MSG_REF_UI_DATE_FIELD_INVALID);
                dateFrom = null;
            } else {
                try {
                    dateFrom = sdf.parse(studentWiseSwipInOutTemplate.getDateFrom());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        Matcher dateToPatternMatcher = datePattern.matcher(studentWiseSwipInOutTemplate.getDateTo());
        if (!studentWiseSwipInOutTemplate.getDateTo().equals(STRING_NULL)) {
            if (!dateToPatternMatcher.find()) {
                errors.rejectValue(VAR_DATE_TO, ERROR_INVALID_MSG_REF_UI_DATE_FIELD_INVALID);
                dateTo = null;
            } else {
                try {
                    dateTo = sdf.parse(studentWiseSwipInOutTemplate.getDateTo());

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            dateTo = null;
        }

        if ((dateFrom != null) && (dateTo != null)) {

            if (dateFrom.after(new Date())) {
                errors.rejectValue(VAR_DATE_FROM, ERROR_FIELD_DATE_FIELD_INCORRECT_FUTURE_FROM);
            }
            if (dateTo.after(new Date())) {
                errors.rejectValue(VAR_DATE_TO, ERROR_FIELD_DATE_FIELD_INCORRECT_FUTURE_TO);
            }

        }

        if ((dateFrom != null) && (dateTo != null)) {
            if (dateFrom.compareTo(dateTo) > 0) {
                errors.rejectValue(VAR_DATE_TO, ERROR_FIELD_REF_UI_DATE_FIELD_INCORRECT);
            }
        }

    }

}

From source file:com.virtusa.akura.student.validator.StudentAttendanceValidator.java

/**
 * Validates the user input for criteria.
 *
 * @param object - Populated object of StudentWiseAttendanceTemplate to validate
 * @param errors - contain errors related to fields.
 * @throws AkuraAppException - throws when exception occurs.
 *//*from ww  w  . j  a v  a 2 s. co  m*/
public void validate(Object object, Errors errors) throws AkuraAppException {

    Date dateFrom = null;

    StudentWiseSwipInOutTemplate studentWiseSwipInOutTemplate = (StudentWiseSwipInOutTemplate) object;

    if (studentWiseSwipInOutTemplate.getDateFrom().equals(STRING_NULL)
            || studentWiseSwipInOutTemplate.getDateTo().equals(STRING_NULL)) {
        errors.rejectValue(VAR_DATE_TO, ERROR_MSG_REF_UI_MANDATORY_FIELD_REQUIRED);
    } else {
        Pattern datePattern = Pattern.compile(ValidatorExpressionUtil.getValidatorPattern(DATE_PATTERN));

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD);
        if (!studentWiseSwipInOutTemplate.getDateFrom().equals(STRING_NULL)) {
            Matcher dateFromPatternMatcher = datePattern.matcher(studentWiseSwipInOutTemplate.getDateFrom());
            if (!dateFromPatternMatcher.find()) {
                errors.rejectValue(VAR_DATE_FROM, ERROR_INVALID_MSG_REF_UI_DATE_FIELD_INVALID);
                dateFrom = null;
            } else {
                try {
                    dateFrom = sdf.parse(studentWiseSwipInOutTemplate.getDateFrom());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        Matcher dateToPatternMatcher = datePattern.matcher(studentWiseSwipInOutTemplate.getDateTo());
        if (!studentWiseSwipInOutTemplate.getDateTo().equals(STRING_NULL)) {
            if (!dateToPatternMatcher.find()) {
                errors.rejectValue(VAR_DATE_TO, ERROR_INVALID_MSG_REF_UI_DATE_FIELD_INVALID);
                dateTo = null;
            } else {
                try {
                    dateTo = sdf.parse(studentWiseSwipInOutTemplate.getDateTo());

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            dateTo = null;
        }

        if ((dateFrom != null) && (dateTo != null)) {

            if (dateFrom.after(new Date())) {
                errors.rejectValue(VAR_DATE_FROM, ERROR_FIELD_DATE_FIELD_INCORRECT_FUTURE_FROM);
            }
            if (dateTo.after(new Date())) {
                errors.rejectValue(VAR_DATE_TO, ERROR_FIELD_DATE_FIELD_INCORRECT_FUTURE_TO);
            }

        }

        if ((dateFrom != null) && (dateTo != null)) {
            if (dateFrom.compareTo(dateTo) > 0) {
                errors.rejectValue(VAR_DATE_TO, ERROR_FIELD_REF_UI_DATE_FIELD_INCORRECT);
            }
        }

    }

}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleCopyPart(HttpServletRequest request, HttpServletResponse response, BlobStore blobStore,
        String containerName, String blobName, String uploadId) throws IOException, S3Exception {
    // TODO: duplicated from handlePutBlob
    String copySourceHeader = request.getHeader("x-amz-copy-source");
    copySourceHeader = URLDecoder.decode(copySourceHeader, "UTF-8");
    if (copySourceHeader.startsWith("/")) {
        // Some clients like boto do not include the leading slash
        copySourceHeader = copySourceHeader.substring(1);
    }/*from  w w w. j a v  a2 s.  com*/
    String[] path = copySourceHeader.split("/", 2);
    if (path.length != 2) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }
    String sourceContainerName = path[0];
    String sourceBlobName = path[1];

    GetOptions options = new GetOptions();
    String range = request.getHeader("x-amz-copy-source-range");
    if (range != null && range.startsWith("bytes=") &&
    // ignore multiple ranges
            range.indexOf(',') == -1) {
        range = range.substring("bytes=".length());
        String[] ranges = range.split("-", 2);
        if (ranges[0].isEmpty()) {
            options.tail(Long.parseLong(ranges[1]));
        } else if (ranges[1].isEmpty()) {
            options.startAt(Long.parseLong(ranges[0]));
        } else {
            options.range(Long.parseLong(ranges[0]), Long.parseLong(ranges[1]));
        }
    }

    String partNumberString = request.getParameter("partNumber");
    if (partNumberString == null) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }
    int partNumber;
    try {
        partNumber = Integer.parseInt(partNumberString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", nfe,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }
    if (partNumber < 1 || partNumber > 10_000) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", (Throwable) null,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }

    // TODO: how to reconstruct original mpu?
    MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId,
            createFakeBlobMetadata(blobStore), new PutOptions());

    Blob blob = blobStore.getBlob(sourceContainerName, sourceBlobName, options);
    if (blob == null) {
        throw new S3Exception(S3ErrorCode.NO_SUCH_KEY);
    }

    BlobMetadata blobMetadata = blob.getMetadata();

    String ifMatch = request.getHeader("x-amz-copy-source-if-match");
    String ifNoneMatch = request.getHeader("x-amz-copy-source-if-modified-since");
    long ifModifiedSince = request.getDateHeader("x-amz-copy-source-if-none-match");
    long ifUnmodifiedSince = request.getDateHeader("x-amz-copy-source-if-unmodified-since");
    String eTag = blobMetadata.getETag();
    if (eTag != null) {
        eTag = maybeQuoteETag(eTag);
        if (ifMatch != null && !ifMatch.equals(eTag)) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
        if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
    }

    Date lastModified = blobMetadata.getLastModified();
    if (lastModified != null) {
        if (ifModifiedSince != -1 && lastModified.compareTo(new Date(ifModifiedSince)) <= 0) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
        if (ifUnmodifiedSince != -1 && lastModified.compareTo(new Date(ifUnmodifiedSince)) >= 0) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
    }

    long contentLength = blobMetadata.getContentMetadata().getContentLength();

    String blobStoreType = getBlobStoreType(blobStore);
    try (InputStream is = blob.getPayload().openStream()) {
        if (blobStoreType.equals("azureblob")) {
            // Azure has a maximum part size of 4 MB while S3 has a minimum
            // part size of 5 MB and a maximum of 5 GB.  Split a single S3
            // part multiple Azure parts.
            long azureMaximumMultipartPartSize = blobStore.getMaximumMultipartPartSize();
            HashingInputStream his = new HashingInputStream(Hashing.md5(), is);
            for (int offset = 0, subPartNumber = 0; offset < contentLength; offset += azureMaximumMultipartPartSize, ++subPartNumber) {
                Payload payload = Payloads.newInputStreamPayload(
                        new UncloseableInputStream(ByteStreams.limit(his, azureMaximumMultipartPartSize)));
                payload.getContentMetadata()
                        .setContentLength(Math.min(azureMaximumMultipartPartSize, contentLength - offset));
                blobStore.uploadMultipartPart(mpu, 10_000 * partNumber + subPartNumber, payload);
            }
            eTag = BaseEncoding.base16().lowerCase().encode(his.hash().asBytes());
        } else {
            Payload payload = Payloads.newInputStreamPayload(is);
            payload.getContentMetadata().setContentLength(contentLength);

            MultipartPart part = blobStore.uploadMultipartPart(mpu, partNumber, payload);
            eTag = part.partETag();
        }
    }

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("CopyObjectResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeSimpleElement(xml, "LastModified", formatDate(lastModified));
        if (eTag != null) {
            writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag));
        }

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:com.example.rachid.myapplication.MyMeteor.java

public ArrayList<Event> getAllEvents(String location, String date) {

    int capacity, assistants, contact_number;
    String id, photo, name, description, place, firstDay, lastDay, sales, webpage, creator;

    Date mFirstDay, mLastDay;/*  w w  w .  j  a  va2  s . co m*/
    Date mCurrentDate = getCurrentDate();
    Date mSearchDate = convertDate(date);
    Log.i(TAG, "ENTRO A MyMeteor:getAllEventsWithDate: CURRENT_DATE: " + mCurrentDate);
    Log.i(TAG, "ENTRO A MyMeteor:getAllEventsWithDate: SEARCH_DATE: " + mSearchDate);

    Event event;
    ArrayList<Event> list = new ArrayList<>();

    try {
        // Get Database
        Database database = mMeteor.getDatabase();

        // Get Collection name is "Events"
        Collection collection = database.getCollection(Events);

        // Get of Collection "Events" where "place" of all events is equal to "location"
        //Query query = collection.whereEqual("place", location);
        // Create a list of events
        //Document[] documents = query.find();

        Document[] documents = collection.find();

        for (Document doc : documents) {

            // Buscamos eventos por localizacion
            place = (String) doc.getField("place");
            if (place.contains(location)) {

                firstDay = (String) doc.getField("firstDay");
                lastDay = (String) doc.getField("lastDay");

                mFirstDay = convertDate(firstDay);
                mLastDay = convertDate(lastDay);

                Log.i(TAG, "ENTRO A MyMeteor:getAllEventsWithDate: FIRST_DAY: " + mFirstDay);
                Log.i(TAG, "ENTRO A MyMeteor:getAllEventsWithDate: LAST_DAY: " + mLastDay);

                // Buscamos eventos que no hayan pasado
                if (mCurrentDate.compareTo(mLastDay) <= 0) {
                    //if ( !mCurrentDate.after( mLastDay ) ) {

                    //Buscamos eventos para la fecha concreta
                    //(firstDay <= dia) && (dia <= lastDay)
                    if ((0 <= mSearchDate.compareTo(mFirstDay)) && (mSearchDate.compareTo(mLastDay) <= 0)) {
                        //if ((mSearchDate.after(mFirstDay)) && (mSearchDate.before(mLastDay))) {

                        //Aadimos este evento al ArrayList
                        id = doc.getId();

                        photo = (String) doc.getField("photo");
                        name = (String) doc.getField("name");
                        description = (String) doc.getField("description");

                        //place = (String) doc.getField("place");
                        //firstDay = (String) doc.getField("firstDay");
                        //lastDay = (String) doc.getField("lastDay");

                        capacity = (int) doc.getField("capacity");
                        assistants = (int) doc.getField("assistants");

                        sales = (String) doc.getField("sales");
                        webpage = (String) doc.getField("webpage");

                        // Esto es asi, porque en la DB del server, a veces este valor se guarda como "int" y otras como "string"
                        // -------------------------------------------------------------------------------
                        Object object = doc.getField("contact_number");
                        //Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:Contact_Number CLASS?: " + o.getClass());
                        if (object instanceof String) {
                            if ((!TextUtils.isEmpty((String) object))) {
                                contact_number = Integer.parseInt((String) object);
                            } else {
                                contact_number = 0;
                            }
                        } else if (object instanceof Integer) {
                            contact_number = (int) object;
                        } else {
                            contact_number = -1; //ERROR ...
                        }
                        // -------------------------------------------------------------------------------

                        creator = (String) doc.getField("creator");

                        event = new Event(id, photo, name, description, place, firstDay, lastDay, capacity,
                                assistants, sales, webpage, contact_number, creator);

                        list.add(event);
                    }
                }
            }
        }

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

    return list;
}

From source file:org.apache.ode.bpel.rtrep.v1.PICK.java

/**
 * @see org.apache.ode.jacob.JacobRunnable#run()
 *///from ww w .ja v  a  2s .com
public void run() {
    PickResponseChannel pickResponseChannel = newChannel(PickResponseChannel.class);
    Date timeout;
    Selector[] selectors;

    try {
        selectors = new Selector[_opick.onMessages.size()];
        int idx = 0;
        for (OPickReceive.OnMessage onMessage : _opick.onMessages) {
            CorrelationKey key = null; // this will be the case for the
            // createInstance activity

            PartnerLinkInstance pLinkInstance = _scopeFrame.resolve(onMessage.partnerLink);
            if (onMessage.matchCorrelation == null && !_opick.createInstanceFlag) {
                // Adding a route for opaque correlation. In this case,
                // correlation is on "out-of-band" session-id
                String sessionId = getBpelRuntime().fetchMySessionId(pLinkInstance);
                key = new CorrelationKey(-1, new String[] { sessionId });
            } else if (onMessage.matchCorrelation != null) {
                if (!getBpelRuntime()
                        .isCorrelationInitialized(_scopeFrame.resolve(onMessage.matchCorrelation))) {
                    // the following should really test if this is a "join"
                    // type correlation...
                    if (!_opick.createInstanceFlag)
                        throw new FaultException(_opick.getOwner().constants.qnCorrelationViolation,
                                "Correlation not initialized.");
                } else {

                    key = getBpelRuntime().readCorrelation(_scopeFrame.resolve(onMessage.matchCorrelation));

                    assert key != null;
                }
            }

            selectors[idx] = new Selector(idx, pLinkInstance, onMessage.operation.getName(),
                    onMessage.operation.getOutput() == null, onMessage.messageExchangeId, key);
            idx++;
        }

        timeout = null;
        for (OPickReceive.OnAlarm onAlarm : _opick.onAlarms) {
            Date dt = onAlarm.forExpr != null
                    ? offsetFromNow(getBpelRuntime().getExpLangRuntime().evaluateAsDuration(onAlarm.forExpr,
                            getEvaluationContext()))
                    : getBpelRuntime().getExpLangRuntime()
                            .evaluateAsDate(onAlarm.untilExpr, getEvaluationContext()).getTime();
            if (timeout == null || timeout.compareTo(dt) > 0) {
                timeout = dt;
                _alarm = onAlarm;
            }
        }
        getBpelRuntime().select(pickResponseChannel, timeout, _opick.createInstanceFlag, selectors);
    } catch (FaultException e) {
        __log.error(e);
        FaultData fault = createFault(e.getQName(), _opick, e.getMessage());
        dpe(_opick.outgoingLinks);
        _self.parent.completed(fault, CompensationHandler.emptySet());
        return;
    }

    // Dead path all the alarms that have no chace of coming first.
    for (OPickReceive.OnAlarm oa : _opick.onAlarms) {
        if (!oa.equals(_alarm)) {
            dpe(oa.activity);
        }
    }

    instance(new WAITING(pickResponseChannel));
}

From source file:org.apache.ode.bpel.rtrep.v2.PICK.java

/**
 * @see org.apache.ode.jacob.JacobRunnable#run()
 *///from  w w  w.java 2s  .  c  om
public void run() {
    PickResponseChannel pickResponseChannel = newChannel(PickResponseChannel.class);
    Date timeout;
    Selector[] selectors;

    try {
        selectors = new Selector[_opick.onMessages.size()];
        int idx = 0;
        for (OPickReceive.OnMessage onMessage : _opick.onMessages) {
            CorrelationKey key = null; // this will be the case for the
            // createInstance activity

            PartnerLinkInstance pLinkInstance = _scopeFrame.resolve(onMessage.partnerLink);
            if (onMessage.matchCorrelation == null && !_opick.createInstanceFlag) {
                // Adding a route for opaque correlation. In this case,
                // correlation is on "out-of-band" session-id
                String sessionId = getBpelRuntime().fetchMySessionId(pLinkInstance);
                key = new CorrelationKey(-1, new String[] { sessionId });
            } else if (onMessage.matchCorrelation != null) {
                if (!getBpelRuntime()
                        .isCorrelationInitialized(_scopeFrame.resolve(onMessage.matchCorrelation))) {
                    // the following should really test if this is a "join"
                    // type correlation...
                    if (!_opick.createInstanceFlag)
                        throw new FaultException(_opick.getOwner().constants.qnCorrelationViolation,
                                "Correlation not initialized.");
                } else {

                    key = getBpelRuntime().readCorrelation(_scopeFrame.resolve(onMessage.matchCorrelation));

                    assert key != null;
                }
            }

            selectors[idx] = new Selector(idx, pLinkInstance, onMessage.operation.getName(),
                    onMessage.operation.getOutput() == null, onMessage.messageExchangeId, key);
            idx++;
        }

        timeout = null;
        for (OPickReceive.OnAlarm onAlarm : _opick.onAlarms) {
            Date dt = onAlarm.forExpr != null
                    ? offsetFromNow(getBpelRuntime().getExpLangRuntime().evaluateAsDuration(onAlarm.forExpr,
                            getEvaluationContext()))
                    : getBpelRuntime().getExpLangRuntime()
                            .evaluateAsDate(onAlarm.untilExpr, getEvaluationContext()).getTime();
            if (timeout == null || timeout.compareTo(dt) > 0) {
                timeout = dt;
                _alarm = onAlarm;
            }
        }
        getBpelRuntime().select(pickResponseChannel, timeout, _opick.createInstanceFlag, selectors);
    } catch (FaultException e) {
        __log.error(e);
        FaultData fault = createFault(e.getQName(), _opick, e.getMessage());
        dpe(_opick.outgoingLinks);
        _self.parent.completed(fault, CompensationHandler.emptySet());
        return;
    }

    // Dead path all the alarms that have no chace of coming first.
    for (OPickReceive.OnAlarm oa : _opick.onAlarms) {
        if (!oa.equals(_alarm)) {
            dpe(oa.activity);
        }
    }

    instance(new WAITING(_scopeFrame, pickResponseChannel));
}

From source file:de.unihannover.l3s.mws.bean.Search.java

public String calculateTimeline(ArrayList<SearchResult> searchResult) {
    List<String> urlAnalyzed = new ArrayList<String>();
    Date dinizio = new Date();
    Timeline timeline1 = new Timeline();
    timeline1.setHeadline("Starting");
    timeline1.setType("default");
    timeline1.setStartDate("2009,1");
    timeline1.setText("Starting Point");
    Asset a = new Asset();
    a.setMedia("aaa");
    a.setCredit("");
    a.setCaption("");
    timeline1.setAsset(a);//ww  w .  j a va2  s .c o m

    timeline1.setDate(new ArrayList<de.unihannover.l3s.mws.model.timeline.Date>());
    // if (this.searchResult!=null)
    for (SearchResult sr : searchResult) {
        System.out.println(sr.getUrl());
        if (sr.getUrl().contains("wikipedia") || sr.getUrl().contains("youtube")
                || sr.getUrl().contains("slideshare") || sr.getUrl().contains("flickr")) {
            de.unihannover.l3s.mws.model.timeline.Date date2 = new de.unihannover.l3s.mws.model.timeline.Date();
            int year = 2009 + (int) (Math.random() * ((2013 - 2009) + 1));
            int month = 1 + (int) (Math.random() * ((12 - 1) + 1));
            date2.setStartDate(year + "," + month);
            date2.setHeadline(sr.getUrl().replace(".", " ").replace("-", " ").replace(",", "").replace("_", " ")
                    .replace("?", "").replace("=", " "));
            date2.setText("");
            Asset a2 = new Asset();
            a2.setCaption("");
            a2.setCredit("");

            if (sr.getUrl().contains("wikipedia")) {
                if (!chechAny(urlAnalyzed, sr.getUrl())) {
                    urlAnalyzed.add(sr.getUrl());
                    SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy,MM");
                    Date d = DateManager.getWikipediaDate(sr.getUrl());
                    if (d != null) {
                        String data1 = FORMATTER.format(d);
                        date2.setStartDate(data1);
                        date2.setAsset(a2);

                        Calendar cal = Calendar.getInstance();
                        cal.setTime(d);
                        cal.add(Calendar.MONTH, -2);

                        if (dinizio.compareTo(cal.getTime()) > 0) {
                            dinizio = cal.getTime();
                            timeline1.setStartDate(FORMATTER.format(dinizio));
                        }

                        a2.setMedia(
                                "http://localhost:8080/mwsace2/javax.faces.resource/img/icon/icon-wikipedia.png.jsf?ln=timeline");
                        timeline1.getDate().add(date2);
                    }
                }
            } else if (sr.getUrl().contains("youtube")) {
                if (!chechAny(urlAnalyzed, sr.getUrl())) {
                    urlAnalyzed.add(sr.getUrl());
                    SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy,MM");
                    Date d = DateManager.getYoutubeDate(sr.getUrl());
                    if (d != null) {
                        String data1 = FORMATTER.format(d);

                        date2.setStartDate(data1);
                        date2.setAsset(a2);

                        Calendar cal = Calendar.getInstance();
                        cal.setTime(d);
                        cal.add(Calendar.MONTH, -2);

                        if (dinizio.compareTo(cal.getTime()) > 0) {
                            dinizio = cal.getTime();
                            timeline1.setStartDate(FORMATTER.format(dinizio));
                        }

                        a2.setMedia(
                                "http://localhost:8080/mwsace2/javax.faces.resource/img/icon/y_icon.png.jsf?ln=timeline");
                        timeline1.getDate().add(date2);
                    }
                }
            } else if (sr.getUrl().contains("slideshare")) {
                if (!chechAny(urlAnalyzed, sr.getUrl()) && sr.getUrl().startsWith("http://www.slideshare.net/")
                        && sr.getUrl().compareTo("http://www.slideshare.net/") != 0
                        && !sr.getUrl().contains("www.slideshare.net/login")) {
                    urlAnalyzed.add(sr.getUrl());
                    SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy,MM");
                    Date d = DateManager.getSlideshareDate(sr.getUrl());
                    if (d != null) {
                        String data1 = FORMATTER.format(d);

                        date2.setStartDate(data1);
                        date2.setAsset(a2);

                        Calendar cal = Calendar.getInstance();
                        cal.setTime(d);
                        cal.add(Calendar.MONTH, -2);

                        if (dinizio.compareTo(cal.getTime()) > 0) {
                            dinizio = cal.getTime();
                            timeline1.setStartDate(FORMATTER.format(dinizio));
                        }

                        a2.setMedia(
                                "http://localhost:8080/mwsace2/javax.faces.resource/img/icon/slideshare-icon.png.jsf?ln=timeline");
                        timeline1.getDate().add(date2);
                    }
                }
            } else if (sr.getUrl().contains("flickr")) {
                a2.setMedia(
                        "http://localhost:8080/mwsace2/javax.faces.resource/img/icon/flickr-icon.png.jsf?ln=timeline");
                date2.setAsset(a2);
                timeline1.getDate().add(date2);
            }

        }
    }
    //else
    //   System.out.println("SR NULL");
    /* de.unihannover.l3s.mws.model.timeline.Date date1=new de.unihannover.l3s.mws.model.timeline.Date();
    date1.setStartDate("2009,2");
    date1.setHeadline("My first experiment in time-lapse photography");
    date1.setText("Nature at its finest in this video.");
    Asset a1=new Asset();
    a1.setMedia("");
    a1.setCaption("");
    a1.setCredit("");
    date1.setAsset(a1);
    timeline1.getDate().add(date1); */

    WholeTimeline wl = new WholeTimeline();
    wl.setTimeline(timeline1);
    if (this.searchResult != null) {
        timeline = (new JSONObject(wl)).toString();
        // timeline=" var timeline = new VMM.Timeline(); timeline.init('"+timeline+"'); ";
        timeline = " $(\"#timeline\").empty(); var timeline = new VMM.Timeline(); timeline.init('" + timeline
                + "'); ";
    } else
        timeline = "";

    System.out.println(timeline);
    return timeline;
}

From source file:com.example.rachid.myapplication.MyMeteor.java

public ArrayList<Event> getAllEvents(String location) {

    int capacity, assistants, contact_number;
    String id, photo, name, description, place, firstDay, lastDay, sales, webpage, creator;

    Date mFirstDay, mLastDay;/*from  ww w . ja va 2s  .  c  o  m*/
    Date mCurrentDate = getCurrentDate();
    Log.i(TAG, "ENTRO A MyMeteor:getAllEvents: CURRENT_DATE: " + mCurrentDate);

    Event event;
    ArrayList<Event> list = new ArrayList<>();

    Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:mMeteor: " + mMeteor);

    try {

        // Get Database
        Database database = mMeteor.getDatabase();

        Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:database: " + database);

        // Get Collection name is "Events"
        Collection collection = database.getCollection(Events);

        Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:collection: " + collection);

        // Get of Collection "Events" where "place" of all events is equal to "location"
        //Query query = collection.whereEqual("place", location);

        // Create a list of events
        //Document[] documents = query.find();

        Document[] documents = collection.find();

        for (Document doc : documents) {

            // Buscamos eventos por localizacion
            place = (String) doc.getField("place");
            if (place.contains(location)) {

                firstDay = (String) doc.getField("firstDay");
                lastDay = (String) doc.getField("lastDay");

                //mFirstDay = convertDate(firstDay);
                mLastDay = convertDate(lastDay);

                //Log.i(TAG, "ENTRO A MyMeteor:getAllEvents: FIRST_DAY: " + mFirstDay);
                Log.i(TAG, "ENTRO A MyMeteor:getAllEvents: LAST_DAY: " + mLastDay);

                // Buscamos eventos que no hayan pasado
                if (mCurrentDate.compareTo(mLastDay) <= 0) {
                    //if ( !mCurrentDate.after(mLastDay) ) {

                    id = doc.getId();

                    photo = (String) doc.getField("photo");
                    name = (String) doc.getField("name");

                    Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:NAME: " + name);
                    Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:IMAGE: " + photo);

                    description = (String) doc.getField("description");

                    //place = (String) doc.getField("place");
                    //firstDay = (String) doc.getField("firstDay");
                    //lastDay = (String) doc.getField("lastDay");

                    //
                    //Object o = doc.getField("capacity");
                    //Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:Capacity CLASS?: " + o.getClass());
                    //

                    capacity = (int) doc.getField("capacity");
                    assistants = (int) doc.getField("assistants");

                    sales = (String) doc.getField("sales");
                    webpage = (String) doc.getField("webpage");

                    // Esto es asi, porque en la DB del server, a veces este valor se guarda como "int" y otras como "string"
                    // -------------------------------------------------------------------------------
                    Object object = doc.getField("contact_number");
                    //Log.i(TAG, "ENTRO A MyMeteor:getAllEvents:Contact_Number CLASS?: " + o.getClass());
                    if (object instanceof String) {
                        if ((!TextUtils.isEmpty((String) object))) {
                            contact_number = Integer.parseInt((String) object);
                        } else {
                            contact_number = 0;
                        }
                    } else if (object instanceof Integer) {
                        contact_number = (int) object;
                    } else {
                        contact_number = -1; //ERROR ...
                    }
                    // -------------------------------------------------------------------------------

                    creator = (String) doc.getField("creator");

                    event = new Event(id, photo, name, description, place, firstDay, lastDay, capacity,
                            assistants, sales, webpage, contact_number, creator);

                    list.add(event);
                }
            }
        }

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

    return list;
}