Example usage for java.util Date setDate

List of usage examples for java.util Date setDate

Introduction

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

Prototype

@Deprecated
public void setDate(int date) 

Source Link

Document

Sets the day of the month of this Date object to the specified value.

Usage

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();// w  ww  . j  av  a  2 s . c om
    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();/*from  w w w  .j av a  2  s.com*/
    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:eu.inmite.apps.smsjizdenka.util.SmsParser.java

private Date parseDate(String text, String datePattern, SimpleDateFormat sdf, SimpleDateFormat sdfTime,
        Ticket ticket) {//from  w w w. j a va 2  s.  co 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.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java

private List<Encounter> randomizeEncounterDates(List<Obs> patientObsList) {
    Integer flag = 0;//w  w  w.  j av  a  2s .  c  o  m
    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:com.krawler.spring.hrms.employee.hrmsEmpDAOImpl.java

public KwlReturnObject salaryGeneratedUpdates(HashMap<String, Object> requestParams) {
    Boolean success = false;/*from   w  w w .  jav a 2s. co  m*/
    Calendar calendar = Calendar.getInstance();
    Date date1;
    Date date2;
    List<Updates> list = new ArrayList<Updates>();
    try {
        Locale locale = null;
        if (requestParams.get("locale") != null) {
            locale = (Locale) requestParams.get("locale");
        }
        DateFormat df = (DateFormat) requestParams.get("df");
        String userid = requestParams.get("userid").toString();
        Date userdate = (Date) requestParams.get("userdate");
        String companyid = requestParams.get("companyid").toString();
        calendar.setTime(userdate);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.MONTH, -(Calendar.MONTH - 1));
        date1 = calendar.getTime();
        date1.setDate(1);
        date2 = calendar.getTime();
        date2.setDate(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String query = "from Payhistory where userID.company.companyID=? and userID.userID=? and salarystatus=? and generatedon is not null and createdon is not null  and paycyclestart is not null and paycyclestart between ? and ?";
        List<Payhistory> recordTotalCount = HibernateUtil.executeQuery(hibernateTemplate, query,
                new Object[] { companyid, userid, 3, date1, date2 });
        Iterator<Payhistory> itr = recordTotalCount.iterator();
        while (itr.hasNext()) {
            Payhistory payhistory = itr.next();
            String updateDiv = "";
            updateDiv += messageSource.getMessage("hrms.common.Alert.salaryGeneratedUpdates",
                    new Object[] { "<font color='green'>" + df.format(payhistory.getPaycyclestart())
                            + "</font> <a href='#' onclick='viewmypayslip()'>", "</a>" },
                    "Salary is generated for month <font color='green'>"
                            + df.format(payhistory.getPaycyclestart())
                            + "</font> <a href='#' onclick='viewmypayslip()'>download</a> payslip.",
                    locale);
            list.add(new Updates(StringUtil.getContentSpan(updateDiv), payhistory.getGeneratedon()));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        success = false;
    } finally {
        return new KwlReturnObject(success, "", "", list, list.size());
    }
}

From source file:com.progym.custom.fragments.CalloriesProgressMonthlyLineFragment.java

public void setLineData3(final Date date, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);/*from   w  ww  .ja v  a  2  s  .  c  o m*/
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                int yMaxAxisValue = 0;
                try {

                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            rlRootGraphLayout.removeView(mChartView);
                        }
                    });

                } catch (Exception edsx) {
                    edsx.printStackTrace();
                }
                date.setDate(1);
                DATE = date;
                // Get amount of days in a month to find out average
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set First day of the month as first month

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                        23, 24, 25, 26, 27, 28, 29, 30, 31 };

                // Creating an XYSeries for Consumed water
                XYSeries callories = new XYSeries("Callories");

                List<Ingridient> list;
                Date dt = date; // **
                // Adding data to Income and Expense Series
                for (int i = 1; i <= daysInMonth; i++) {
                    // get all water records consumed per this month
                    list = DataBaseUtils.getAllFoodConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM_DD));
                    // init "average" data
                    int totalCallories = 0;
                    for (Ingridient ingridient : list) {
                        totalCallories += ingridient.kkal;
                    }
                    callories.add(i, totalCallories);
                    dt = DateUtils.addDays(dt, 1);
                    yMaxAxisValue = Math.max(yMaxAxisValue, totalCallories);
                }

                // Creating a dataset to hold each series
                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                // Adding Income Series to the dataset
                dataset.addSeries(callories);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer calloriesRenderer = new XYSeriesRenderer();
                calloriesRenderer.setColor(Color.rgb(220, 255, 110));
                calloriesRenderer.setFillPoints(true);
                calloriesRenderer.setLineWidth(3);
                calloriesRenderer.setDisplayChartValues(true);

                // Creating a XYMultipleSeriesRenderer to customize the whole chart
                final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
                // multiRenderer.setXLabels(0);

                for (int i = 0; i < x.length; i++) {
                    multiRenderer.addXTextLabel(i, String.valueOf(x[i]));
                }

                // Adding incomeRenderer and expenseRenderer to multipleRenderer
                // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
                // should be same
                multiRenderer.setChartTitle(String.format("Callories statistic"));
                multiRenderer.setXTitle(Utils.getSpecificDateValue(DATE, "MMM") + " of "
                        + Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY));
                multiRenderer.setYTitle(getActivity().getResources().getString(R.string.callories_consumption));
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(calloriesRenderer);
                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                multiRenderer.setXLabelsAngle(20);
                multiRenderer.setYAxisMax(yMaxAxisValue + 200);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(31);
                multiRenderer.setXAxisMin(1);
                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mChartView = ChartFactory.getLineChartView(getActivity(), dataset, multiRenderer);
                        rlRootGraphLayout.addView(mChartView, 0);
                        if (isLeftIn) {
                            rightIn.setDuration(1000);
                            mChartView.startAnimation(rightIn);
                        } else {
                            leftIn.setDuration(1000);
                            mChartView.startAnimation(leftIn);
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
            ringProgressDialog.dismiss();
        }
    }).start();

}

From source file:com.progym.custom.fragments.FoodProgressMonthlyLineFragment.java

public void setLineData3(final Date date, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);//from  www  . ja  v  a 2  s .co  m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                int yMaxAxisValue = 0;

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rlRootGraphLayout.removeView(graphView);
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }

                    }
                });

                date.setDate(1);
                DATE = date;
                // Get amount of days in a month to find out average
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set First day of the month as first month

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                        23, 24, 25, 26, 27, 28, 29, 30, 31 };

                // Creating an XYSeries for Consumed water
                XYSeries protein = new XYSeries("Protein");
                XYSeries fat = new XYSeries("Fat");
                XYSeries carbs = new XYSeries("Carbs");

                List<Ingridient> list;
                Date dt = date; // *
                // Adding data to Income and Expense Series
                for (int i = 1; i <= daysInMonth; i++) {
                    // get all water records consumed per this month
                    list = DataBaseUtils.getAllFoodConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM_DD));
                    // init "average" data
                    double totalProtein = 0, totalFat = 0, totalCarbs = 0;
                    if (null != list) {
                        for (Ingridient ingridient : list) {
                            totalProtein += ingridient.protein;
                            totalFat += ingridient.fat;
                            totalCarbs += ingridient.carbohydrates;
                        }
                    }

                    protein.add(i, (double) Math.round(totalProtein * 100) / 100);
                    fat.add(i, (double) Math.round(totalFat * 100) / 100);
                    carbs.add(i, (double) Math.round(totalCarbs * 100) / 100);
                    // calories.add(i, totalCallories);
                    dt = DateUtils.addDays(dt, 1);

                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalProtein);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalFat);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalCarbs);
                }

                // Creating a dataset to hold each series
                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                // Adding Income Series to the dataset
                dataset.addSeries(protein);
                dataset.addSeries(carbs);
                dataset.addSeries(fat);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer proteinRenderer = new XYSeriesRenderer();
                proteinRenderer.setColor(Color.rgb(50, 255, 50));
                proteinRenderer.setFillPoints(true);
                proteinRenderer.setLineWidth(3);
                proteinRenderer.setDisplayChartValues(true);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer fatRenderer = new XYSeriesRenderer();
                fatRenderer.setColor(Color.rgb(123, 111, 00));
                fatRenderer.setFillPoints(true);
                fatRenderer.setLineWidth(3);
                fatRenderer.setDisplayChartValues(true);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer carbsRenderer = new XYSeriesRenderer();
                carbsRenderer.setColor(Color.rgb(222, 13, 11));
                carbsRenderer.setFillPoints(true);
                carbsRenderer.setLineWidth(3);
                carbsRenderer.setDisplayChartValues(true);

                // Creating a XYMultipleSeriesRenderer to customize the whole chart
                final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
                // multiRenderer.setXLabels(0);

                for (int i = 0; i < x.length; i++) {
                    multiRenderer.addXTextLabel(i, String.valueOf(x[i]));
                }

                // Adding incomeRenderer and expenseRenderer to multipleRenderer
                // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
                // should be same
                multiRenderer.setChartTitle(String.format("Protein/Carbs/Fat statistic "));
                multiRenderer.setXTitle(Utils.getSpecificDateValue(DATE, "MMM") + " of "
                        + Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY));
                multiRenderer.setYTitle("Amount (g)          ");
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(proteinRenderer);
                multiRenderer.addSeriesRenderer(carbsRenderer);
                multiRenderer.addSeriesRenderer(fatRenderer);

                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                multiRenderer.setXLabelsAngle(20);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(31);
                multiRenderer.setXAxisMin(1);
                multiRenderer.setYAxisMax(yMaxAxisValue + 30);
                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            graphView = ChartFactory.getLineChartView(getActivity(), dataset, multiRenderer);
                            rlRootGraphLayout.addView(graphView, 0);

                            if (isLeftIn) {
                                rightIn.setDuration(1000);
                                graphView.startAnimation(rightIn);
                            } else {
                                leftIn.setDuration(1000);
                                graphView.startAnimation(leftIn);
                            }
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
            ringProgressDialog.dismiss();
        }
    }).start();

}

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

/**
 * Create bitstream in item.//from   w ww .java  2  s  .co 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.progym.custom.fragments.WaterProgressYearlyLineFragment.java

public void setLineData3(final Date date, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);/*from  www .j  av  a  2 s .  com*/
    ringProgressDialog.setCancelable(true);

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                int yMaxAxisValue = 0;
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rlRootGraphLayout.removeView(mChartView);
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }
                    }
                });

                DATE = date;
                // 31 - Amount of days in a month
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set January as first month
                date.setMonth(0);
                date.setDate(1);

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

                // Creating an XYSeries for Consumed water
                XYSeries consumedSeries = new XYSeries("Consumed");

                List<WaterConsumed> list;
                // int userShouldConsume = (int) DataBaseUtils.getWaterUserShouldConsumePerDay();
                Date dt = date; // *
                // Adding data to Income and Expense Series
                for (int i = 0; i < x.length; i++) {
                    // get all water records consumed per this month
                    list = DataBaseUtils.getAllWaterConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM));
                    // init "average" data
                    int averageWaterConsumedOnYaxis = 0;
                    for (int j = 0; j < list.size(); j++) {
                        // calculate sum of all water consumed by user in a month
                        averageWaterConsumedOnYaxis += list.get(j).volumeConsumed;
                    }
                    averageWaterConsumedOnYaxis = averageWaterConsumedOnYaxis / daysInMonth;
                    consumedSeries.add(i, averageWaterConsumedOnYaxis);
                    // normaSeries.add(i, userShouldConsume);
                    dt = DateUtils.addMonths(dt, 1);
                    yMaxAxisValue = Math.max(yMaxAxisValue, averageWaterConsumedOnYaxis);
                }

                // Creating a dataset to hold each series
                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                // Adding Expense Series to dataset
                // dataset.addSeries(normaSeries);
                // Adding Income Series to the dataset
                dataset.addSeries(consumedSeries);

                // Creating XYSeriesRenderer to customize incomeSeries
                XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
                incomeRenderer.setColor(Color.rgb(50, 255, 50));
                incomeRenderer.setFillPoints(true);
                incomeRenderer.setLineWidth(2);
                incomeRenderer.setDisplayChartValues(true);

                /*
                 * // Creating XYSeriesRenderer to customize expenseSeries
                 * XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
                 * expenseRenderer.setColor(Color.rgb(80, 220, 80));
                 * expenseRenderer.setFillPoints(true);
                 * expenseRenderer.setLineWidth(2);
                 * expenseRenderer.setDisplayChartValues(true);
                 */

                // Creating a XYMultipleSeriesRenderer to customize the whole chart
                final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
                multiRenderer.setXLabels(0);

                for (int i = 0; i < x.length; i++) {
                    multiRenderer.addXTextLabel(i, ActivityWaterProgress.months_short[i]);
                }

                // Adding incomeRenderer and expenseRenderer to multipleRenderer
                // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
                // should be same
                multiRenderer.setChartTitle(String.format("Water statistic for %s year",
                        Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY)));
                multiRenderer.setXTitle("Months");
                multiRenderer.setYTitle("Water volume (ml)");
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(incomeRenderer);
                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                // multiRenderer.addSeriesRenderer(expenseRenderer);
                multiRenderer.setXLabelsAngle(30);
                // multiRenderer.setBackgroundColor(Color.parseColor("#B3FFFFFF"));
                // multiRenderer.setApplyBackgroundColor(true);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(11.5);
                multiRenderer.setXAxisMin(-0.5);
                multiRenderer.setYAxisMax(yMaxAxisValue + (yMaxAxisValue / 5));
                multiRenderer.setYAxisMin(-0.1);

                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setBarSpacing(0.1);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mChartView = ChartFactory.getBarChartView(getActivity(), dataset, multiRenderer,
                                Type.DEFAULT);

                        rlRootGraphLayout.addView(mChartView, 0);
                        if (isLeftIn) {
                            rightIn.setDuration(1000);
                            mChartView.startAnimation(rightIn);
                        } else {
                            leftIn.setDuration(1000);
                            mChartView.startAnimation(leftIn);
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
            ringProgressDialog.dismiss();
        }
    }).start();

}

From source file:com.progym.custom.fragments.CalloriesProgressYearlyLineFragment.java

public void setYearProgressData(final Date date, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);//from  ww  w .j a va 2  s.c o  m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                int yMaxAxisValue = 0;

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rlRootGraphLayout.removeView(viewChart);
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }
                    }
                });

                DATE = date;
                // Get amount of days in a month to find out average
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set January as first month
                date.setMonth(0);
                date.setDate(1);

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                CategorySeries seriesCallories = new CategorySeries("Callories");

                List<Ingridient> list;
                Date dt = date; // *
                for (int element : x) {
                    list = DataBaseUtils.getAllFoodConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM));

                    // init "average" data
                    int totalCallories = 0;
                    for (Ingridient ingridient : list) {
                        totalCallories += ingridient.kkal;
                    }
                    // add value to series
                    seriesCallories.add(totalCallories / daysInMonth);
                    // calculate maximum Y axis values
                    yMaxAxisValue = Math.max(yMaxAxisValue, totalCallories / daysInMonth);
                    // increment month
                    dt = DateUtils.addMonths(dt, 1);
                }

                int[] colors = new int[] { getActivity().getResources().getColor(R.color.purple) };
                final XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
                setChartSettings(renderer,
                        String.format("Callories statistic for %s year",
                                Utils.getSpecificDateValue(DATE, "yyyy")),
                        "Months", "Calories consumption", 0.7, 12.3, 0, yMaxAxisValue + 30, Color.GRAY,
                        Color.LTGRAY);

                renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
                renderer.getSeriesRendererAt(0).setChartValuesTextSize(15f);
                renderer.setXLabels(0);
                renderer.setClickEnabled(false);
                renderer.setZoomEnabled(false);
                renderer.setPanEnabled(false, false);
                renderer.setZoomButtonsVisible(false);
                renderer.setPanLimits(new double[] { 1, 11 });
                renderer.setShowGrid(true);
                renderer.setShowLegend(true);
                renderer.setFitLegend(true);

                for (int i = 0; i < ActivityWaterProgress.months_short.length; i++) {
                    renderer.addXTextLabel(i + 1, ActivityWaterProgress.months_short[i]);

                }
                dataset.addSeries(seriesCallories.toXYSeries());

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        viewChart = ChartFactory.getBarChartView(getActivity(), dataset, renderer,
                                Type.DEFAULT);
                        rlRootGraphLayout.addView(viewChart, 0);

                        if (isLeftIn) {
                            rightIn.setDuration(1000);
                            viewChart.startAnimation(rightIn);
                        } else {
                            leftIn.setDuration(1000);
                            viewChart.startAnimation(leftIn);
                        }
                    }
                });

            } catch (Exception e) {
            }
            ringProgressDialog.dismiss();
        }
    }).start();

}