Example usage for java.util Date setYear

List of usage examples for java.util Date setYear

Introduction

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

Prototype

@Deprecated
public void setYear(int year) 

Source Link

Document

Sets the year of this Date object to be the specified value plus 1900.

Usage

From source file:accountgen.controller.Controller.java

private void setBday(Document doc, Person p) {
    Element bday = doc.select(".bday").first();
    Date bd = new Date();

    Date date = null;//from   w ww  .j a  va2  s  . c  om
    try {
        date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(bday.text().split(" ")[0]);
    } catch (ParseException ex) {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH);
    bd.setMonth(month);
    bd.setDate(Integer.parseInt(bday.text().split(" ")[1].replace(",", "")));
    bd.setYear(Integer.parseInt(bday.text().split(",")[1].substring(1, 5)) - 1900);
    p.setBirthday(bd);
}

From source file:eu.inmite.apps.smsjizdenka.util.SmsParser.java

private Date parseDate(String text, String datePattern, SimpleDateFormat sdf, SimpleDateFormat sdfTime,
        Ticket ticket) {/*www . j  a  va  2  s . c o m*/
    Matcher m = Pattern.compile(datePattern).matcher(text);
    if (m.find()) {
        String d = m.group(1);
        if (!isEmpty(d)) {
            d = d.replaceAll(";", "");

            for (int i = 0; i < 2; i++) {
                final Date date;
                try {
                    if (i == 0) {
                        date = sdf.parse(d); // full date/time
                    } else if (i == 1 && sdfTime != null) {
                        date = sdfTime.parse(d); // only time
                    } else {
                        break;
                    }
                } catch (Exception e) {
                    continue;
                }

                if (i == 1 && ticket != null && ticket.validFrom != null) {
                    final Date prevDate = ticket.validFrom;
                    date.setYear(prevDate.getYear());
                    date.setMonth(prevDate.getMonth());
                    date.setDate(prevDate.getDate());
                }

                return date;
            }
        }
    }

    throw new RuntimeException("Cannot parse date from the message " + text);
}

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  w w . 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: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 a v a 2  s  .c om
    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.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 ww w  . jav  a2  s .c o  m
    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:com.fitforbusiness.nafc.dashboard.DashBoardFragment.java

private void loadSessions(String date) {

    Calendar calendar = Calendar.getInstance();
    date = String.format("%d-%02d-%02d", calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) + 1),
            calendar.get(Calendar.DAY_OF_MONTH));
    Date stDate = null;/*  w  w w . j  av a 2s . c  o  m*/
    Date edDate = null;
    try {
        stDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        stDate.setTime(stDate.getTime() - 1000);
        edDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        edDate.setTime(edDate.getTime() + (24 * 60 * 60 * 1000));
        edDate.setTime(edDate.getTime() - 1000);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    ArrayList<HashMap<String, Object>> mapArrayList = new ArrayList<>();
    SQLiteDatabase sqlDB;
    try {
        sqlDB = DatabaseHelper.instance().getReadableDatabase();

        String query = "select  " + Table.Sessions.ID + " , " + Table.Sessions.START_DATE + " , "
                + Table.Sessions.START_TIME + " , " + Table.Sessions.SESSION_STATUS + " , "
                + Table.Sessions.GROUP_ID + " , " + Table.Sessions.IS_NATIVE + " , "
                + Table.Sessions.RECURRENCE_RULE + " , " + Table.Sessions.TITLE + " , "
                + Table.Sessions.SESSION_TYPE + "  " + " from " + Table.Sessions.TABLE_NAME + " where "
                + Table.DELETED + " = 0 " + " and ( " + Table.Sessions.START_DATE + " =  datetime(\'" + date
                + "\') " + " OR  " + Table.Sessions.RECURRENCE_RULE + " IS NOT NULL " + "       OR "
                + Table.Sessions.RECURRENCE_RULE + " != '' ) ";

        Log.d("query is ", query);
        assert sqlDB != null;
        Cursor cursor = sqlDB.rawQuery(query, null);

        Log.d("Calendar", "Month Count = " + cursor.getCount());

        LinkedHashMap<String, Object> row;
        while (cursor.moveToNext()) {

            if (cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)) == null
                    || cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)).equals("")) {

                row = new LinkedHashMap<String, Object>();

                long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID));
                int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE));
                rowData = getImageName(groupSessionId + "", session_type);

                row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID)));
                row.put("name",
                        Utils.dateConversionForRow(
                                cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE))) + " "
                                + Utils.timeFormatAMPM(
                                        cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME))));

                row.put("rowId", groupSessionId);
                row.put("type", session_type);

                if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) {

                    row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE)));
                    row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus));
                    Log.d("Calendar", "native events");
                } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) {
                    row.put("photo", rowData.getImageName());
                    row.put("secondLabel", rowData.getPersonName());
                    row.put("thirdLabel",
                            status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]);

                    Log.d("Calendar", "app events");
                }
                Log.d("Calendar", (String) row.get("secondLabel"));
                mapArrayList.add(row);
            } else {
                String rule = cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE));

                RecurrenceRule recRule = new RecurrenceRule(rule);
                RecurrenceRule.Freq freq = recRule.getFreq();

                Date d = new SimpleDateFormat("dd MMM yyyy").parse(Utils.formatConversionSQLite(
                        cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE))));

                switch (freq) {
                case MONTHLY:
                    d.setMonth(stDate.getMonth());
                case YEARLY:
                    d.setYear(stDate.getYear());
                }

                if (freq == RecurrenceRule.Freq.MONTHLY || freq == RecurrenceRule.Freq.YEARLY) {
                    if (!(d.after(stDate) && d.before(edDate)))
                        continue;
                }

                ArrayList<Calendar> dates;
                dates = CalendarMonthViewFragment.ruleOccurONDate(rule, stDate, edDate);

                Log.e("RecurRule", "size = " + dates.size());

                if (dates.size() > 0) {
                    row = new LinkedHashMap<String, Object>();

                    if (freq == RecurrenceRule.Freq.DAILY || freq == RecurrenceRule.Freq.WEEKLY) {
                        if (d.after(dates.get(0).getTime()))
                            continue;
                    }

                    long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID));
                    int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE));
                    rowData = getImageName(groupSessionId + "", session_type);
                    row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID)));
                    row.put("name", Utils.formatConversionDateOnly(stDate) + " " + Utils.timeFormatAMPM(
                            cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME))));

                    row.put("rowId", groupSessionId);
                    row.put("type", session_type);

                    if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) {

                        row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE)));
                        row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus));
                        Log.d("Calendar", "native events");
                    } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) {
                        row.put("photo", rowData.getImageName());
                        row.put("secondLabel", rowData.getPersonName());
                        row.put("thirdLabel",
                                status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]);

                        Log.d("Calendar", "app events");
                    }
                    Log.d("Calendar", (String) row.get("secondLabel"));
                    mapArrayList.add(row);
                }
            }
        }
        cursor.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    CustomAsyncTaskListAdapter adapter = new CustomAsyncTaskListAdapter(getActivity(),
            R.layout.calendar_day_view_session_row, R.id.ivRowImage, R.id.tvFirstName, R.id.tvSecondLabel,
            R.id.tvThirdLabel, mapArrayList);
    sessionList.setAdapter(adapter);
}

From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java

private List<Encounter> randomizeEncounterDates(List<Obs> patientObsList) {
    Integer flag = 0;//from   www  .j  a  va 2 s .c  om
    List<Date> randomizedEncounterDateList = new ArrayList<Date>();
    List<Encounter> en = new ArrayList<Encounter>();
    for (Obs o : patientObsList) {
        en.add(o.getEncounter());
    }
    int year, month, date;
    try {
        for (int i = 0; i < patientObsList.size(); i++) {
            Date d = new Date();
            if (flag == 0) {
                d.setDate(en.get(0).getEncounterDatetime().getDate());
                d.setMonth(en.get(0).getEncounterDatetime().getMonth());
                d.setYear(en.get(0).getEncounterDatetime().getYear());
                flag = 1;
            } else {
                d.setDate(en.get(i - 1).getEncounterDatetime().getDate());
                d.setMonth(en.get(i - 1).getEncounterDatetime().getMonth());
                d.setYear(en.get(i - 1).getEncounterDatetime().getYear());
            }
            year = d.getYear() + 1900;
            month = d.getMonth();
            date = d.getDate();

            //Randomize
            year = randBetween(year + 1, year + 2);
            month = randBetween(month, 12);
            date = randBetween(date, 30);

            //Set date
            d.setYear(year - 1900);
            d.setMonth(month);
            d.setDate(date);
            en.get(i).setEncounterDatetime(d);
            randomizedEncounterDateList.add(d);
        }
    } catch (APIException e) {
        log.error("Exception in randomizing encounter dates", e);
    }
    return en;
}

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

/**
 * Create bitstream in item./*from   w  ww.  ja  v a2 s  .c  om*/
 *
 * @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.krawler.spring.crm.common.crmManagerDAOImpl.java

/**
 * To convert a date and time selected separately by user into corresponding combined datetime
 * from users selected timezone to systems timezone
 *
 * The first step is to keep track of the time difference in order to change the date if required.
 * Two time only objects dtold and dtcmp are created for this purpose.
 *
 * The date passed and the time passed that are in system timezone are formatted without
 * timezone and then parsed into the required timezone and then the time values are set
 * back to the date value sent./*from  ww w  . j  a v a 2 s  . c  om*/
 *
 **/
public Date converttz(String timeZoneDiff, Date dt, String time) {
    Calendar cal = Calendar.getInstance();
    try {
        if (timeZoneDiff == null || timeZoneDiff.isEmpty()) {
            timeZoneDiff = "-7:00";
        }
        String val;
        SimpleDateFormat sdf = new SimpleDateFormat("HHmm 'Hrs'");
        Date dtold = sdf.parse("0000 Hrs");
        if (!time.endsWith("Hrs")) {
            sdf = new SimpleDateFormat("hh:mm a");
            dtold = sdf.parse("00:00 AM");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        sdf2.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed

        Date dt1 = sdf.parse(time); // Setting the passed time to the date object in system timezone

        sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed
        Date dtcmp = sdf.parse(time); // Parsing the time to timezone using passed values
        dt1.setMonth(dt.getMonth()); // Setting the date values sent to the system time only value
        dt1.setDate(dt.getDate());
        dt1.setYear(dt.getYear());
        dt1 = sdf2.parse(sdf1.format(dt1)); // Parsing datetime into required timezone
        dt.setHours(dt1.getHours()); // Setting the time values into the sent date
        dt.setMinutes(dt1.getMinutes());
        dt.setSeconds(0);
        cal.setTime(dt);
        if (dtcmp.compareTo(dtold) < 0) { // Comparing for time value change
            cal.add(Calendar.DATE, -1); //  in order to change the date accordingly
        }
        dtold.setDate(2);
        if (dtcmp.compareTo(dtold) > 0 || dtcmp.compareTo(dtold) == 0) {
            cal.add(Calendar.DATE, 1);
        }

    } catch (ParseException ex) {
        System.out.println(ex);
    } finally {
        return cal.getTime();
    }
}

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

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

    zcView.setGrouped(true);/*w ww .  j  ava2  s.c  o m*/
    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();

}