Example usage for java.util Date setSeconds

List of usage examples for java.util Date setSeconds

Introduction

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

Prototype

@Deprecated
public void setSeconds(int seconds) 

Source Link

Document

Sets the seconds of this Date to the specified value.

Usage

From source file:com.netflix.spinnaker.front50.model.GcsStorageService.java

@VisibleForTesting
public void scheduleWriteLastModified(String daoTypeName) {
    Date when = new Date();
    when.setSeconds(when.getSeconds() + 2);
    GcsStorageService service = this;
    Runnable task = new Runnable() {
        public void run() {
            // Release the scheduled update lock, and perform the actual update
            scheduledUpdateLock(daoTypeName).set(false);
            log.info("RUNNING {}", daoTypeName);
            service.writeLastModified(daoTypeName);
        }/*from  www.  j  av  a2 s.c  o  m*/
    };
    if (scheduledUpdateLock(daoTypeName).compareAndSet(false, true)) {
        log.info("Scheduling deferred update {} timestamp.", daoTypeName);
        taskScheduler.schedule(task, when);
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorTest.java

public void testGoodTransform() throws Exception {
    IPentahoSession session = new StandaloneSession("test");
    KettleSystemListener.environmentInit(session);
    ModelInfo info = createModel();/* w  ww.j a  v  a  2 s.c  o m*/
    CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta());

    gen.preview(session);

    DataRow rows[] = info.getData();
    assertNotNull(rows);
    assertEquals(235, rows.length);

    Date testDate = new Date();
    testDate.setDate(1);
    testDate.setHours(0);
    testDate.setMinutes(0);
    testDate.setMonth(0);
    testDate.setSeconds(0);
    testDate.setYear(110);

    // test the first row
    // test the data types
    DataRow row = rows[0];
    assertNotNull(row);
    Object cells[] = row.getCells();
    assertNotNull(cells);
    //    assertEquals( 8, cells.length );
    assertTrue(cells[0] instanceof Long);
    assertTrue(cells[1] instanceof Double);
    assertTrue(cells[2] instanceof Long);
    assertTrue(cells[3] instanceof Date);
    assertTrue(cells[4] instanceof String);
    assertTrue(cells[5] instanceof Long);
    assertTrue(cells[6] instanceof Double);
    assertTrue(cells[7] instanceof Boolean);
    // test the values
    assertEquals((long) 3, cells[0]);
    assertEquals(25677.96525, cells[1]);
    assertEquals((long) 1231, cells[2]);
    assertEquals(testDate.getYear(), ((Date) cells[3]).getYear());
    assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth());
    assertEquals(testDate.getDate(), ((Date) cells[3]).getDate());
    assertEquals(testDate.getHours(), ((Date) cells[3]).getHours());
    //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
    assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds());

    //    assertEquals( testDate, cells[3] );
    assertEquals("Afghanistan", cells[4]);
    assertEquals((long) 11, cells[5]);
    assertEquals(111.9090909, cells[6]);
    assertEquals(false, cells[7]);

    // test the second row
    testDate.setDate(2);
    // test the data types
    row = rows[1];
    assertNotNull(row);
    cells = row.getCells();
    assertNotNull(cells);
    assertTrue(cells[0] instanceof Long);
    assertTrue(cells[1] instanceof Double);
    assertTrue(cells[2] instanceof Long);
    assertTrue(cells[3] instanceof Date);
    assertTrue(cells[4] == null);
    assertTrue(cells[5] instanceof Long);
    assertTrue(cells[6] instanceof Double);
    assertTrue(cells[7] instanceof Boolean);
    // test the values
    assertEquals((long) 4, cells[0]);
    assertEquals(24261.81026, cells[1]);
    assertEquals((long) 1663, cells[2]);
    assertEquals(testDate.getYear(), ((Date) cells[3]).getYear());
    assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth());
    assertEquals(testDate.getDate(), ((Date) cells[3]).getDate());
    assertEquals(testDate.getHours(), ((Date) cells[3]).getHours());
    //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
    assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds());

    //    assertEquals( testDate, cells[3] );
    assertEquals(null, cells[4]); // IfNull value does not seem to work
    assertEquals((long) 7, cells[5]);
    assertEquals(237.5714286, cells[6]);
    assertEquals(true, cells[7]);

}

From source file:at.general.solutions.android.ical.parser.ICalParserThread.java

private Date parseIcalDate(String dateLine) {
    try {//from  w ww .  j av a  2  s.c  om
        dateLine = StringUtils.replace(dateLine, ";", "");
        Date date = null;
        if (dateLine.contains(ICalTag.DATE_TIMEZONE)) {
            String[] parts = StringUtils.split(dateLine, ":");
            ICAL_DATETIME_FORMAT.setTimeZone(TimeZone
                    .getTimeZone(parts[0].substring(ICalTag.DATE_TIMEZONE.length(), parts[0].length())));
            date = ICAL_DATETIME_FORMAT.parse(parts[1]);
            ICAL_DATETIME_FORMAT.setTimeZone(icalDefaultTimeZone);
        } else if (dateLine.contains(ICalTag.DATE_VALUE)) {
            String[] parts = StringUtils.split(dateLine, ":");
            date = ICAL_DATE_FORMAT.parse(parts[1]);
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
        } else {
            dateLine = StringUtils.replace(dateLine, ":", "");
            date = ICAL_DATETIME_FORMAT.parse(dateLine);
        }
        return date;
    } catch (ParseException e) {
        Log.e(LOG_TAG, "Cant't parse date!", e);
        return null;
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java

public void testLoadTable1() throws Exception {
    IPentahoSession session = new StandaloneSession("test");
    KettleSystemListener.environmentInit(session);
    ModelInfo info = createModel();/*from  www .  ja  v a 2  s.com*/
    CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta());

    // create the model
    String tableName = info.getStageTableName();
    try {
        gen.execSqlStatement(getDropTableStatement(tableName), getDatabaseMeta(), null);
    } catch (CsvTransformGeneratorException e) {
        // table might not be there yet, it is OK
    }

    // generate the database table
    gen.createOrModifyTable(session);

    // load the table
    loadTable(gen, info, true, session);

    // check the results
    long rowCount = this.getRowCount(tableName);
    assertEquals((long) 235, rowCount);
    DatabaseMeta databaseMeta = getDatabaseMeta();
    assertNotNull(databaseMeta);
    Database database = new Database(databaseMeta);
    assertNotNull(database);
    database.connect();

    Connection connection = null;
    Statement stmt = null;
    ResultSet sqlResult = null;

    try {
        connection = database.getConnection();
        assertNotNull(connection);
        stmt = database.getConnection().createStatement();

        // check the first row
        Date testDate = new Date();
        testDate.setDate(1);
        testDate.setHours(0);
        testDate.setMinutes(0);
        testDate.setMonth(0);
        testDate.setSeconds(0);
        testDate.setYear(110);
        boolean ok = stmt.execute("select * from " + tableName);
        assertTrue(ok);
        sqlResult = stmt.getResultSet();
        assertNotNull(sqlResult);
        ok = sqlResult.next();
        assertTrue(ok);

        // test the values
        assertEquals((long) 3, sqlResult.getLong(1));
        assertEquals(25677.96525, sqlResult.getDouble(2));
        assertEquals((long) 1231, sqlResult.getLong(3));
        assertEquals(testDate.getYear(), sqlResult.getDate(4).getYear());
        assertEquals(testDate.getMonth(), sqlResult.getDate(4).getMonth());
        assertEquals(testDate.getDate(), sqlResult.getDate(4).getDate());
        assertEquals(testDate.getHours(), sqlResult.getTime(4).getHours());
        //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
        assertEquals(testDate.getSeconds(), sqlResult.getTime(4).getSeconds());

        //    assertEquals( testDate, cells[3] );
        assertEquals("Afghanistan", sqlResult.getString(5));
        assertEquals((long) 11, sqlResult.getLong(6));
        assertEquals(111.9090909, sqlResult.getDouble(7));
        assertEquals(false, sqlResult.getBoolean(8));
    } finally {
        sqlResult.close();
        stmt.close();
        connection.close();
    }

}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java

public void testGoodTransform() throws Exception {
    IPentahoSession session = new StandaloneSession("test");
    KettleSystemListener.environmentInit(session);
    String KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL = System.getProperty("KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL",
            "N");
    ModelInfo info = createModel();/* w  w w .j  ava  2s.  c  o  m*/
    CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta());

    gen.preview(session);

    DataRow rows[] = info.getData();
    assertNotNull(rows);
    assertEquals(235, rows.length);

    Date testDate = new Date();
    testDate.setDate(1);
    testDate.setHours(0);
    testDate.setMinutes(0);
    testDate.setMonth(0);
    testDate.setSeconds(0);
    testDate.setYear(110);

    // test the first row
    // test the data types
    DataRow row = rows[0];
    assertNotNull(row);
    Object cells[] = row.getCells();
    assertNotNull(cells);
    //    assertEquals( 8, cells.length );
    assertTrue(cells[0] instanceof Long);
    assertTrue(cells[1] instanceof Double);
    assertTrue(cells[2] instanceof Long);
    assertTrue(cells[3] instanceof Date);
    assertTrue(cells[4] instanceof String);
    assertTrue(cells[5] instanceof Long);
    assertTrue(cells[6] instanceof Double);
    assertTrue(cells[7] instanceof Boolean);
    // test the values
    assertEquals((long) 3, cells[0]);
    assertEquals(25677.96525, cells[1]);
    assertEquals((long) 1231, cells[2]);
    assertEquals(testDate.getYear(), ((Date) cells[3]).getYear());
    assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth());
    assertEquals(testDate.getDate(), ((Date) cells[3]).getDate());
    assertEquals(testDate.getHours(), ((Date) cells[3]).getHours());
    //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
    assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds());

    //    assertEquals( testDate, cells[3] );
    assertEquals("Afghanistan", cells[4]);
    assertEquals((long) 11, cells[5]);
    assertEquals(111.9090909, cells[6]);
    assertEquals(false, cells[7]);

    // test the second row
    testDate.setDate(2);
    // test the data types
    row = rows[1];
    assertNotNull(row);
    cells = row.getCells();
    assertNotNull(cells);
    assertTrue(cells[0] instanceof Long);
    assertTrue(cells[1] instanceof Double);
    assertTrue(cells[2] instanceof Long);
    assertTrue(cells[3] instanceof Date);
    if ("Y".equals(KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL)) {
        assertTrue("".equals(cells[4]));
    } else {
        assertTrue(cells[4] == null);
    }
    assertTrue(cells[5] instanceof Long);
    assertTrue(cells[6] instanceof Double);
    assertTrue(cells[7] instanceof Boolean);
    // test the values
    assertEquals((long) 4, cells[0]);
    assertEquals(24261.81026, cells[1]);
    assertEquals((long) 1663, cells[2]);
    assertEquals(testDate.getYear(), ((Date) cells[3]).getYear());
    assertEquals(testDate.getMonth(), ((Date) cells[3]).getMonth());
    assertEquals(testDate.getDate(), ((Date) cells[3]).getDate());
    assertEquals(testDate.getHours(), ((Date) cells[3]).getHours());
    //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
    assertEquals(testDate.getSeconds(), ((Date) cells[3]).getSeconds());

    //    assertEquals( testDate, cells[3] );
    if ("Y".equals(KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL)) {
        assertEquals("", cells[4]);
        assertEquals(cells[4], "");
    } else {
        assertEquals(null, cells[4]); // IfNull value does not seem to work
    }

    assertEquals((long) 7, cells[5]);
    assertEquals(237.5714286, cells[6]);
    assertEquals(true, cells[7]);

}

From source file:org.sakaiproject.evaluation.beans.EvalBeanUtils.java

/**
 * Sets all the system defaults for this evaluation object
 * and ensures all required fields are correctly set,
 * use this whenever you create a new evaluation <br/>
 * This is guaranteed to be non-destructive (i.e. it will not replace existing values
 * but it will fixup any required fields which are nulls to default values),
 * will force null due date to be non-null but will respect the {@link EvalEvaluation#useDueDate} flag
 * //from  w  w w . ja  v  a2s .  co m
 * @param eval an {@link EvalEvaluation} object (can be persisted or new)
 * @param evaluationType a type constant of EvalConstants#EVALUATION_TYPE_*,
 * if left null then {@link EvalConstants#EVALUATION_TYPE_EVALUATION} is used
 */
public void setEvaluationDefaults(EvalEvaluation eval, String evaluationType) {

    // set the type to the default to ensure not null
    if (eval.getType() == null) {
        eval.setType(EvalConstants.EVALUATION_TYPE_EVALUATION);
    }

    // set to the supplied type if supplied and do any special settings if needed based on the type
    if (evaluationType != null) {
        eval.setType(evaluationType);
    }

    // only do these for new evals
    if (eval.getId() == null) {
        if (eval.getState() == null) {
            eval.setState(EvalConstants.EVALUATION_STATE_PARTIAL);
        }
    }

    // make sure the dates are set
    Calendar calendar = new GregorianCalendar();
    Date now = new Date();

    // if default start hour is set, use it for start time (must be tomorrow as eval cannot start in the past).
    Integer hour = (Integer) settings.get(EvalSettings.EVAL_DEFAULT_START_HOUR);
    if (hour != null) {
        // add 1 day to make it tomorrow
        now.setTime(now.getTime() + 86400000L);
        // set desired hour
        now.setHours(hour);
        now.setMinutes(0);
        now.setSeconds(0);
    }

    calendar.setTime(now);
    if (eval.getStartDate() == null) {
        eval.setStartDate(now);
        LOG.debug("Setting start date to default of: " + eval.getStartDate());
    } else {
        calendar.setTime(eval.getStartDate());
    }

    if (eval.useDueDate != null && !eval.useDueDate) {
        // allow evals which are open forever
        eval.setDueDate(null);
        eval.setStopDate(null);
        eval.setViewDate(null);
    } else {
        // using the due date
        calendar.add(Calendar.DATE, 1); // +1 day
        if (eval.getDueDate() == null) {
            // default the due date to the end of the start date + 1 day
            Date endOfDay = EvalUtils.getEndOfDayDate(calendar.getTime());
            eval.setDueDate(endOfDay);
            LOG.debug("Setting due date to default of: " + eval.getDueDate());
        } else {
            calendar.setTime(eval.getDueDate());
        }

        boolean useStopDate;
        if (eval.useStopDate != null && !eval.useStopDate) {
            useStopDate = false;
        } else {
            useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
        }
        if (useStopDate) {
            // assign stop date to equal due date for now
            if (eval.getStopDate() == null) {
                eval.setStopDate(eval.getDueDate());
                LOG.debug("Setting stop date to default of: " + eval.getStopDate());
            }
        } else {
            eval.setStopDate(null);
        }

        boolean useViewDate;
        if (eval.useViewDate != null && !eval.useViewDate) {
            useViewDate = false;
        } else {
            useViewDate = (Boolean) settings.get(EvalSettings.EVAL_USE_VIEW_DATE);
        }
        if (useViewDate) {
            // assign default view date
            calendar.add(Calendar.DATE, 1);
            if (eval.getViewDate() == null) {
                // default the view date to the today + 2
                eval.setViewDate(calendar.getTime());
                LOG.debug("Setting view date to default of: " + eval.getViewDate());
            }
        } else {
            eval.setViewDate(null);
        }
    }

    // handle the view dates default
    Boolean useSameViewDates = (Boolean) settings.get(EvalSettings.EVAL_USE_SAME_VIEW_DATES);
    Date sharedDate = eval.getViewDate() == null ? eval.getDueDate() : eval.getViewDate();
    if (eval.getStudentsDate() == null || useSameViewDates) {
        eval.setStudentsDate(sharedDate);
    }
    if (eval.getInstructorsDate() == null || useSameViewDates) {
        eval.setInstructorsDate(sharedDate);
    }

    // results viewable settings
    Date studentsDate;
    Boolean studentsView = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS);
    if (studentsView != null) {
        eval.setStudentViewResults(studentsView);
    }

    Date instructorsDate;
    Boolean instructorsView = (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS);
    if (instructorsView != null) {
        eval.setInstructorViewResults(instructorsView);
    }

    // Added by EVALSYS-1063. Modified by EVALSYS-1176.
    // Will modify the value of EvalEvaluation.instructorViewAllResults property iff current value is null.
    // Will use value of EvalSettings.INSTRUCTOR_ALLOWED_VIEW_ALL_RESULTS setting if available, false otherwise.
    Boolean instructorsAllView = eval.getInstructorViewAllResults();
    if (instructorsAllView == null) {
        Boolean instructorsAllViewSetting = (Boolean) settings
                .get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_ALL_RESULTS);
        if (instructorsAllViewSetting == null) {
            eval.setInstructorViewAllResults(Boolean.FALSE);
        } else {
            eval.setInstructorViewAllResults(instructorsAllViewSetting);
        }
    }

    // Section awareness default controlled by sakai.property
    if (eval.getSectionAwareness() == null || !eval.getSectionAwareness()) {
        eval.setSectionAwareness(EVALSYS_SECTION_AWARE_DEFAULT);
    }

    // Results sharing default controlled by sakai.property
    if (eval.getResultsSharing() == null) {
        if (!EvalConstants.SHARING_VISIBLE.equals(EVALSYS_RESULTS_SHARING_DEFAULT)
                && !EvalConstants.SHARING_PRIVATE.equals(EVALSYS_RESULTS_SHARING_DEFAULT)
                && !EvalConstants.SHARING_PUBLIC.equals(EVALSYS_RESULTS_SHARING_DEFAULT)) {
            eval.setResultsSharing(EvalConstants.SHARING_VISIBLE);
        } else {
            eval.setResultsSharing(EVALSYS_RESULTS_SHARING_DEFAULT);
        }
    }

    // Instructors view results default controlled by sakai.property
    if ((Boolean) eval.getInstructorViewResults() == null) {
        eval.setInstructorViewResults(EVALSYS_INSTRUCTOR_VIEW_RESPONSES_DEFAULT);
    }
    if (eval.getInstructorViewAllResults() == null) {
        eval.setInstructorViewAllResults(EVALSYS_INSTRUCTOR_VIEW_RESPONSES_DEFAULT);
    }

    if (EvalConstants.SHARING_PRIVATE.equals(eval.getResultsSharing())) {
        eval.setStudentViewResults(false);
        eval.setInstructorViewResults(false);
        eval.setInstructorViewAllResults(false);
    } else if (EvalConstants.SHARING_PUBLIC.equals(eval.getResultsSharing())) {
        eval.setStudentViewResults(true);
        eval.setInstructorViewResults(true);
        eval.setInstructorViewAllResults(true);
        studentsDate = eval.getViewDate();
        eval.setStudentsDate(studentsDate);
        instructorsDate = eval.getViewDate();
        eval.setInstructorsDate(instructorsDate);
    }

    // student completion settings
    if (eval.getBlankResponsesAllowed() == null) {
        Boolean blankAllowed = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
        if (blankAllowed == null) {
            blankAllowed = false;
        }
        eval.setBlankResponsesAllowed(blankAllowed);
    }

    if (eval.getModifyResponsesAllowed() == null) {
        Boolean modifyAllowed = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES);
        if (modifyAllowed == null) {
            modifyAllowed = false;
        }
        eval.setModifyResponsesAllowed(modifyAllowed);
    }

    if (eval.getUnregisteredAllowed() == null) {
        eval.setUnregisteredAllowed(Boolean.FALSE);
    }

    if (eval.getAllRolesParticipate() == null) {
        Boolean allRolesParticipate = (Boolean) settings.get(EvalSettings.ALLOW_ALL_SITE_ROLES_TO_RESPOND);
        if (allRolesParticipate == null) {
            allRolesParticipate = false;
        }
        eval.setAllRolesParticipate(allRolesParticipate);
    }

    // fix up the reminder days to the default
    if (eval.getReminderDays() == null) {
        Integer reminderDays = 1;
        Integer defaultReminderDays = (Integer) settings.get(EvalSettings.DEFAULT_EMAIL_REMINDER_FREQUENCY);
        if (defaultReminderDays != null) {
            reminderDays = defaultReminderDays;
        }
        eval.setReminderDays(reminderDays);
    }

    // set the reminder email address to the default
    if (eval.getReminderFromEmail() == null) {
        // email from address control
        String from = (String) settings.get(EvalSettings.FROM_EMAIL_ADDRESS);
        // https://bugs.caret.cam.ac.uk/browse/CTL-1525 - default to admin address if option set
        Boolean useAdminEmail = (Boolean) settings.get(EvalSettings.USE_ADMIN_AS_FROM_EMAIL);
        if (useAdminEmail) {
            // try to get the email address for the owner (eval admin)
            EvalUser owner = commonLogic.getEvalUserById(commonLogic.getCurrentUserId());
            if (owner != null && owner.email != null && !"".equals(owner.email)) {
                from = owner.email;
            }
        }
        eval.setReminderFromEmail(from);
    }

    // admin settings
    if (eval.getInstructorOpt() == null) {
        String instOpt = (String) settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE);
        if (instOpt == null) {
            instOpt = EvalConstants.INSTRUCTOR_REQUIRED;
        }
        eval.setInstructorOpt(instOpt);
    }
}

From source file:org.dspace.rest.ItemsResource.java

/**
 * Create bitstream in item./*from  w ww . j  a  va  2s. c  o  m*/
 *
 * @param itemId      Id of item in DSpace.
 * @param inputStream Data of bitstream in inputStream.
 * @param headers     If you want to access to item under logged user into context.
 *                    In headers must be set header "rest-dspace-token" with passed
 *                    token from login method.
 * @return Returns bitstream with status code OK(200). If id of item is
 * invalid , it returns status code NOT_FOUND(404). If user is not
 * allowed to write to item, UNAUTHORIZED(401).
 * @throws WebApplicationException It is thrown by these exceptions: SQLException, when was
 *                                 problem with reading/writing from/to database.
 *                                 AuthorizeException, when was problem with authorization to
 *                                 item and add bitstream to item. IOException, when was problem
 *                                 with creating file or reading from inpustream.
 *                                 ContextException. When was problem with creating context of
 *                                 DSpace.
 */
// TODO Add option to add bitstream by URI.(for very big files)
@POST
@Path("/{item_id}/bitstreams")
@ApiOperation(value = "Create a bitstream in an item by using the internal DSpace item identifier.", response = org.dspace.rest.common.Bitstream.class)
public Bitstream addItemBitstream(
        @ApiParam(value = "The identifier of the item.", required = true) @PathParam("item_id") Integer itemId,

        @ApiParam(value = "InputStream object", required = true) InputStream inputStream,

        @ApiParam(value = "The name of the bitstream.", required = true) @QueryParam("name") String name,

        @ApiParam(value = "The description of the bitstream.", required = false) @QueryParam("description") String description,

        @ApiParam(value = "The group id of the policy group.", required = false) @QueryParam("groupId") Integer groupId,

        @ApiParam(value = "The year of the policy start date.", required = false) @QueryParam("year") Integer year,

        @ApiParam(value = "The month of the policy start date.", required = false) @QueryParam("month") Integer month,

        @ApiParam(value = "The day of the policy start date.", required = false) @QueryParam("day") Integer day,

        @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
        @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers,
        @Context HttpServletRequest request) throws WebApplicationException {

    log.info("Adding bitstream to item(id=" + itemId + ").");
    org.dspace.core.Context context = null;
    Bitstream bitstream = null;

    try {
        context = createContext();
        org.dspace.content.Item dspaceItem = findItem(context, itemId, org.dspace.core.Constants.WRITE);

        writeStats(dspaceItem, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor, headers, request,
                context);

        // Is better to add bitstream to ORIGINAL bundle or to item own?
        log.trace("Creating bitstream in item.");
        Bundle bundle = null;
        org.dspace.content.Bitstream dspaceBitstream = null;
        Bundle[] bundles = dspaceItem.getBundles("ORIGINAL");
        if (bundles != null && bundles.length != 0) {
            bundle = bundles[0]; // There should be only one bundle ORIGINAL.
        }
        if (bundle == null) {
            log.trace("Creating bundle in item.");
            dspaceBitstream = dspaceItem.createSingleBitstream(inputStream);
        } else {
            log.trace("Getting bundle from item.");
            dspaceBitstream = bundle.createBitstream(inputStream);
        }

        dspaceBitstream.setSource("DSpace Rest api");

        // Set bitstream name and description
        if (name != null) {
            if (BitstreamResource.getMimeType(name) == null) {
                dspaceBitstream.setFormat(BitstreamFormat.findUnknown(context));
            } else {
                dspaceBitstream.setFormat(
                        BitstreamFormat.findByMIMEType(context, BitstreamResource.getMimeType(name)));
            }
            dspaceBitstream.setName(name);
        }
        if (description != null) {
            dspaceBitstream.setDescription(description);
        }

        dspaceBitstream.update();

        // Create policy for bitstream
        if (groupId != null) {
            bundles = dspaceBitstream.getBundles();
            for (Bundle dspaceBundle : bundles) {
                List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = dspaceBundle
                        .getBitstreamPolicies();

                // Remove default bitstream policies
                List<org.dspace.authorize.ResourcePolicy> policiesToRemove = new ArrayList<org.dspace.authorize.ResourcePolicy>();
                for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) {
                    if (policy.getResourceID() == dspaceBitstream.getID()) {
                        policiesToRemove.add(policy);
                    }
                }
                for (org.dspace.authorize.ResourcePolicy policy : policiesToRemove) {
                    bitstreamsPolicies.remove(policy);
                }

                org.dspace.authorize.ResourcePolicy dspacePolicy = org.dspace.authorize.ResourcePolicy
                        .create(context);
                dspacePolicy.setAction(org.dspace.core.Constants.READ);
                dspacePolicy.setGroup(Group.find(context, groupId));
                dspacePolicy.setResourceID(dspaceBitstream.getID());
                dspacePolicy.setResource(dspaceBitstream);
                dspacePolicy.setResourceType(org.dspace.core.Constants.BITSTREAM);
                if ((year != null) || (month != null) || (day != null)) {
                    Date date = new Date();
                    if (year != null) {
                        date.setYear(year - 1900);
                    }
                    if (month != null) {
                        date.setMonth(month - 1);
                    }
                    if (day != null) {
                        date.setDate(day);
                    }
                    date.setHours(0);
                    date.setMinutes(0);
                    date.setSeconds(0);
                    dspacePolicy.setStartDate(date);
                }

                dspacePolicy.update();
                dspaceBitstream.updateLastModified();
            }
        }

        dspaceBitstream = org.dspace.content.Bitstream.find(context, dspaceBitstream.getID());
        bitstream = new Bitstream(dspaceBitstream, "");

        context.complete();

    } catch (SQLException e) {
        processException("Could not create bitstream in item(id=" + itemId + "), SQLException. Message: " + e,
                context);
    } catch (AuthorizeException e) {
        processException(
                "Could not create bitstream in item(id=" + itemId + "), AuthorizeException. Message: " + e,
                context);
    } catch (IOException e) {
        processException("Could not create bitstream in item(id=" + itemId + "), IOException Message: " + e,
                context);
    } catch (ContextException e) {
        processException("Could not create bitstream in item(id=" + itemId + "), ContextException Message: "
                + e.getMessage(), context);
    } finally {
        processFinally(context);
    }

    log.info("Bitstream(id=" + bitstream.getId() + ") was successfully added into item(id=" + itemId + ").");
    return bitstream;
}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata_last2month(String SENSOR_KEY, String SENSOR_TOKEN)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    /*/*w  w w . ja  v  a 2  s .  c  o  m*/
     * Get local UTC time (now) to request data to server
     */
    //TODO verify with Bart if shall request UTC or local time (guessed UTC)
    Date d = new Date(); // already return UTC
    //long moja_data = d.getTime() - (d.getTimezoneOffset() * 60 * 1000); // calculate
    // data/time
    // (milliseconds)
    // at local timzone
    //d.setTime(moja_data);

    d.setHours(00);
    d.setSeconds(00);
    d.setMinutes(00);

    HttpResponse response = null;
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet(
                "https://" + api_server_ip + "/sensor/" + SENSOR_KEY + "?version=1.0&token=" + SENSOR_TOKEN
                        + "&start=" + ((d.getTime() / 1000) - 5184000) + "&resolution=day&unit=watt"));

        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:org.egov.egf.commons.EgovCommon.java

/**
 * @description - get the list of BudgetUsage based on various parameters
 * @param queryParamMap - HashMap<String, Object> queryParamMap will have data required for the query Query Parameter Map keys
 * are - fundId,ExecutionDepartmentId ,functionId,moduleId,financialYearId ,budgetgroupId,fromDate,toDate and Order By
 * @return//w w w .ja  v a 2s.c om
 */

@SuppressWarnings("unchecked")
public List<BudgetUsage> getListBudgetUsage(final Map<String, Object> queryParamMap) {

    final StringBuffer query = new StringBuffer();
    List<BudgetUsage> listBudgetUsage = null;
    query.append("select bu from BudgetUsage bu,BudgetDetail bd where  bu.budgetDetail.id=bd.id");
    final Map<String, String> mandatoryFields = new HashMap<String, String>();
    final List<AppConfigValues> appConfigList = appConfigValuesService.getConfigValuesByModuleAndKey(
            FinancialConstants.MODULE_NAME_APPCONFIG, "DEFAULTTXNMISATTRRIBUTES");
    for (final AppConfigValues appConfigVal : appConfigList) {
        final String value = appConfigVal.getValue();
        final String header = value.substring(0, value.indexOf("|"));
        final String mandate = value.substring(value.indexOf("|") + 1);
        if (mandate.equalsIgnoreCase("M"))
            mandatoryFields.put(header, "M");
    }
    if (isNotNull(mandatoryFields.get("fund")) && !isNotNull(queryParamMap.get("fundId")))
        throw new ValidationException(Arrays.asList(new ValidationError("fund", "fund cannot be null")));
    else if (isNotNull(queryParamMap.get("fundId")))
        query.append(" and bd.fund.id=").append(Integer.valueOf(queryParamMap.get("fundId").toString()));
    if (isNotNull(mandatoryFields.get("department")) && !isNotNull(queryParamMap.get("ExecutionDepartmentId")))
        throw new ValidationException(
                Arrays.asList(new ValidationError("department", "department cannot be null")));
    else if (isNotNull(queryParamMap.get("ExecutionDepartmentId")))
        query.append(" and bd.executingDepartment.id=")
                .append(Integer.valueOf(queryParamMap.get("ExecutionDepartmentId").toString()));
    if (isNotNull(mandatoryFields.get("function")) && !isNotNull(queryParamMap.get("functionId")))
        throw new ValidationException(
                Arrays.asList(new ValidationError("function", "function cannot be null")));
    else if (isNotNull(queryParamMap.get("functionId")))
        query.append(" and bd.function.id=").append(Long.valueOf(queryParamMap.get("functionId").toString()));

    if (isNotNull(queryParamMap.get("moduleId")))
        query.append(" and bu.moduleId=").append(Integer.valueOf(queryParamMap.get("moduleId").toString()));
    if (isNotNull(queryParamMap.get("financialYearId")))
        query.append(" and bu.financialYearId=")
                .append(Integer.valueOf(queryParamMap.get("financialYearId").toString()));
    if (isNotNull(queryParamMap.get("budgetgroupId")))
        query.append(" and bd.budgetGroup.id=")
                .append(Long.valueOf(queryParamMap.get("budgetgroupId").toString()));
    if (isNotNull(queryParamMap.get("fromDate")))
        query.append(" and bu.updatedTime >=:from");
    if (isNotNull(queryParamMap.get("toDate")))
        query.append(" and bu.updatedTime <=:to");
    if (isNotNull(queryParamMap.get("Order By")))
        query.append(" Order By ").append(queryParamMap.get("Order By"));
    else
        query.append(" Order By bu.updatedTime");

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Budget Usage Query >>>>>>>> " + query.toString());
    final Query query1 = persistenceService.getSession().createQuery(query.toString());
    if (isNotNull(queryParamMap.get("fromDate")))
        query1.setTimestamp("from", (Date) queryParamMap.get("fromDate"));
    if (isNotNull(queryParamMap.get("toDate"))) {
        final Date date = (Date) queryParamMap.get("toDate");
        date.setMinutes(59);
        date.setHours(23);
        date.setSeconds(59);
        query1.setTimestamp("to", date);
    }

    listBudgetUsage = query1.list();
    return listBudgetUsage;

}

From source file:com.zoho.creator.jframework.XMLParser.java

private static void parseAndSetCalendarRecords(ZCView zcView, Node calendarNode) {

    zcView.setGrouped(true);/* ww  w.j  av a  2 s  .c om*/
    NodeList eventsList = calendarNode.getChildNodes();
    int year = zcView.getRecordsMonthYear().getTwo() - 1900;
    int month = zcView.getRecordsMonthYear().getOne();

    GregorianCalendar cureentmnthcalendar = new GregorianCalendar();
    Date currentDate = new Date();

    for (int i = 0; i < eventsList.getLength(); i++) {
        Node eventNode = eventsList.item(i);
        NamedNodeMap eventAttrMap = eventNode.getAttributes();
        long recordid = Long.parseLong(eventAttrMap.getNamedItem("id").getNodeValue()); //No I18N
        String title = getChildNodeValue(eventNode, "title"); //eventAttrMap.getNamedItem("title").getNodeValue(); //No I18N
        boolean isAllDay = Boolean.parseBoolean(eventAttrMap.getNamedItem("allDay").getNodeValue()); //No I18N
        // 07/31/2013 08:00:00
        String dateFormat = "MM/dd/yyyy HH:mm:ss"; //No I18N
        if (isAllDay) {
            dateFormat = "MM/dd/yyyy"; //No I18N
        }

        Date startTime = getDateValue(eventAttrMap.getNamedItem("start").getNodeValue(), dateFormat); //No I18N

        ZCRecord record = zcView.getRecord(recordid);

        record.setEventTitle(title);
        if (isAllDay) {
            zcView.setIsAllDay(isAllDay);

            Node endNode = eventAttrMap.getNamedItem("end");//No I18N
            Date endTime = null;
            if (endNode != null) {
                endTime = getDateValue(endNode.getNodeValue(), dateFormat);
            }

            int startDay = -1;
            if (startTime != null) {
                startDay = startTime.getDate();
            }

            int endDay = -1;
            if (endTime != null) {
                endDay = endTime.getDate();
            }

            if (endDay != -1) {

                currentDate.setDate(1);
                currentDate.setMonth(month);
                currentDate.setYear(year);
                currentDate.setMinutes(0);
                currentDate.setHours(0);
                currentDate.setSeconds(0);

                cureentmnthcalendar.setTime(currentDate);

                cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, -6);
                currentDate = cureentmnthcalendar.getTime();

                for (int j = 0; j < 42; j++) {
                    if ((currentDate.getDate() == startTime.getDate()
                            && currentDate.getMonth() == startTime.getMonth()
                            && currentDate.getYear() == startTime.getYear())
                            || (currentDate.after(startTime) && currentDate.before(endTime))
                            || (currentDate.getDate() == endTime.getDate()
                                    && currentDate.getMonth() == endTime.getMonth()
                                    && currentDate.getYear() == endTime.getYear())) {

                        zcView.setEvent(record, currentDate);
                    }
                    cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, 1);
                    currentDate = cureentmnthcalendar.getTime();
                }
                //Collections.sort(eventRecords);
            }

            record.setEventDate(startTime);
        } else {
            // 07/31/2013 08:00:00
            Date endTime = getDateValue(eventAttrMap.getNamedItem("end").getNodeValue(), dateFormat); //No I18N
            record.setStartTime(startTime);
            record.setEndTime(endTime);

            Calendar startCalendar = new GregorianCalendar();
            startCalendar.setTime(startTime);
            startCalendar.set(Calendar.HOUR_OF_DAY, 0);
            startCalendar.set(Calendar.MINUTE, 0);
            startCalendar.set(Calendar.SECOND, 0);
            startCalendar.set(Calendar.MILLISECOND, 0);

            Calendar endCalendar = new GregorianCalendar();
            endCalendar.setTime(endTime);
            endCalendar.set(Calendar.HOUR_OF_DAY, 0);
            endCalendar.set(Calendar.MINUTE, 0);
            endCalendar.set(Calendar.SECOND, 0);
            endCalendar.set(Calendar.MILLISECOND, 0);

            Date eventDate = new Date(startCalendar.getTimeInMillis());
            zcView.setEvent(record, eventDate);
            while ((startCalendar.get(Calendar.YEAR) != endCalendar.get(Calendar.YEAR))
                    || (startCalendar.get(Calendar.MONTH) != endCalendar.get(Calendar.MONTH))
                    || (startCalendar.get(Calendar.DATE) != endCalendar.get(Calendar.DATE))) {
                startCalendar.add(Calendar.DATE, 1);
                eventDate = new Date(startCalendar.getTimeInMillis());
                zcView.setEvent(record, eventDate);
            }
        }
    }

    List<ZCGroup> zcGroups = zcView.getGroups();
    HashMap<Date, List<ZCRecord>> eventsMap = zcView.getEventRecordsMap();
    SortedSet<Date> keys = new TreeSet<Date>(eventsMap.keySet());

    for (Date eventDate : keys) {
        List<ZCRecord> eventRecords = eventsMap.get(eventDate);
        List<String> groupHeaderValues = new ArrayList<String>();
        SimpleDateFormat dateFormat = new SimpleDateFormat(zcView.getDateFormat()); //No I18N
        groupHeaderValues.add(dateFormat.format(eventDate));
        ZCGroup zcGroup = new ZCGroup(groupHeaderValues);
        zcGroups.add(zcGroup);
        for (int i = 0; i < eventRecords.size(); i++) {
            ZCRecord eventRecord = eventRecords.get(i);
            zcGroup.addRecord(eventRecord);
        }
    }
    zcView.sortRecordsForCalendar();

}