List of usage examples for java.util Date setMinutes
@Deprecated public void setMinutes(int minutes)
From source file:org.dspace.rest.ItemsResource.java
/** * Create bitstream in item.//from w ww. ja v a 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); /*// ww w . j av a2s .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//from w ww .j a v a 2s .co m */ @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);// w ww .j av a 2 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(); }
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.// w w w .j ava 2 s. c o m * **/ 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:org.egov.dao.budget.BudgetDetailsHibernateDAO.java
/** * @description - get the list of BudgetUsage based on various parameters * @param queryParamMap// w ww . j av a 2 s . c om * - HashMap<String, Object> queryParamMap will have data * required for the query the queryParamMap contain values :- the * mis attribute values passed in the query map will be validated * with the appconfig value of key=budgetaryCheck_groupby_values * financialyearid - optional ExecutionDepartmentId - mandatory * -if:department present in the app config value - optional * -else fundId - mandatory -if:fund present in the app config * value - optional -else schemeId - mandatory -if:Scheme present * in the app config value - optional -else functionId - * mandatory -if:function present in the app config value - * optional -else subschemeId - mandatory -if:Subscheme present * in the app config value - optional -else functionaryId - * mandatory -if:functionary present in the app config value - * optional -else boundaryId - mandatory -if:boundary present in * the app config value - optional -else moduleId - optional * financialYearId -optional budgetgroupId -optional fromDate * -optional toDate -optional Order By - optional if passed then * only Budgetary appropriation number and reference number is * accepted, if not passed then default order by is date. * @return */ @Override @SuppressWarnings("unchecked") public List<BudgetUsage> getListBudgetUsage(final Map<String, Object> queryParamMap) { final StringBuffer query = new StringBuffer(); final Map<String, String> grpByVls = new HashMap<String, String>(); List<BudgetUsage> listBudgetUsage = null; query.append("select bu from BudgetUsage bu,BudgetDetail bd where bu.budgetDetail.id=bd.id"); final List<AppConfigValues> list = appConfigValuesService.getConfigValuesByModuleAndKey(EGF, BUDGETARY_CHECK_GROUPBY_VALUES); if (list.isEmpty()) throw new ValidationException(EMPTY_STRING, "budgetaryCheck_groupby_values is not defined in AppConfig"); final AppConfigValues appConfigValues = list.get(0); if (appConfigValues.getValue().indexOf(",") != 1) { // if there are more // than one comma // separated values // for key = // budgetaryCheck_groupby_values final String[] values = StringUtils.split(appConfigValues.getValue(), ","); for (final String value : values) grpByVls.put(value, value); } else grpByVls.put(appConfigValues.getValue(), appConfigValues.getValue()); if (!isNull(grpByVls.get("fund"))) if (isNull(queryParamMap.get("fundId"))) throw new ValidationException(EMPTY_STRING, "Fund is required"); else query.append(" and bd.fund.id=").append(Integer.valueOf(queryParamMap.get("fundId").toString())); if (!isNull(grpByVls.get("department"))) if (isNull(queryParamMap.get("ExecutionDepartmentId"))) throw new ValidationException(EMPTY_STRING, "Department is required"); else query.append(" and bd.executingDepartment.id=") .append(Integer.valueOf(queryParamMap.get("ExecutionDepartmentId").toString())); if (!isNull(grpByVls.get("function"))) if (isNull(queryParamMap.get("functionId"))) throw new ValidationException(EMPTY_STRING, "Function is required"); else query.append(" and bd.function.id=") .append(Long.valueOf(queryParamMap.get("functionId").toString())); if (!isNull(grpByVls.get("scheme"))) if (isNull(queryParamMap.get("schemeId"))) throw new ValidationException(EMPTY_STRING, "Scheme is required"); else query.append(" and bd.scheme.id=") .append(Integer.valueOf(queryParamMap.get("schemeId").toString())); if (!isNull(grpByVls.get("subscheme"))) if (isNull(queryParamMap.get("subschemeId"))) throw new ValidationException(EMPTY_STRING, "SubScheme is required"); else query.append(" and bd.subScheme.id=") .append(Integer.valueOf(queryParamMap.get("subschemeId").toString())); if (!isNull(grpByVls.get(Constants.FUNCTIONARY))) if (isNull(queryParamMap.get("functionaryId"))) throw new ValidationException(EMPTY_STRING, "Functionary is required"); else query.append(" and bd.functionary.id=") .append(Integer.valueOf(queryParamMap.get("functionaryId").toString())); if (!isNull(grpByVls.get("boundary"))) if (isNull(queryParamMap.get("boundaryId"))) throw new ValidationException(EMPTY_STRING, "Boundary is required"); else query.append(" and bd.boundary.id=") .append(Integer.valueOf(queryParamMap.get("boundaryId").toString())); if (!isNull(queryParamMap.get("moduleId"))) query.append(" and bu.moduleId=").append(Integer.valueOf(queryParamMap.get("moduleId").toString())); if (!isNull(queryParamMap.get("financialYearId"))) query.append(" and bu.financialYearId=") .append(Integer.valueOf(queryParamMap.get("financialYearId").toString())); if (!isNull(queryParamMap.get("budgetgroupId"))) query.append(" and bd.budgetGroup.id=") .append(Long.valueOf(queryParamMap.get("budgetgroupId").toString())); if (!isNull(queryParamMap.get("fromDate"))) query.append(" and bu.updatedTime >=:from"); if (!isNull(queryParamMap.get("toDate"))) query.append(" and bu.updatedTime <=:to"); if (!isNull(queryParamMap.get("Order By"))) { if (queryParamMap.get("Order By").toString().indexOf("appropriationnumber") == -1 && queryParamMap.get("Order By").toString().indexOf("referenceNumber") == -1) throw new ValidationException(EMPTY_STRING, "order by value can be only Budgetary appropriation number or Reference number or both"); else 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 = getCurrentSession().createQuery(query.toString()); if (!isNull(queryParamMap.get("fromDate"))) query1.setTimestamp("from", (Date) queryParamMap.get("fromDate")); if (!isNull(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.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private String replaceDateParameters(String jpql, List<Date> dtParams) throws ParseException { if (jpql.contains(IConstants.DT_SEP)) { String[] split = jpql.split(IConstants.DT_SEP); int j = 0; SimpleDateFormat sdf = new SimpleDateFormat(IConstants.DT_YYYY_MM_DD); for (int i = 1; i < split.length; i++) { if (split[i] != null && split[i].length() > 0 && !split[i].startsWith(" ")) { try { Date dt = sdf.parse(split[i]); String last = split[i - 1].trim(); if (last.endsWith("<") || last.endsWith("<=")) { dt.setHours(23); dt.setMinutes(59); dt.setSeconds(59); } else if (last.endsWith(">") || last.endsWith(">=")) { dt.setHours(0);//from ww w .ja v a 2s.co m dt.setMinutes(0); dt.setSeconds(0); } dtParams.add(dt); split[i] = ":dt" + j; j++; } catch (Exception e) { } } } jpql = ""; for (int i = 0; i < split.length; i++) { jpql = jpql + split[i]; } } return jpql; }
From source file:br.gov.jfrj.siga.ex.bl.ExBL.java
/** * Calcula quais as marcas cada mobil ter com base nas movimentaes que * foram feitas no documento.//from w w w. j a va 2 s .c o m * * @param mob */ private SortedSet<ExMarca> calcularMarcadores(ExMobil mob) { SortedSet<ExMarca> set = calcularMarcadoresTemporalidade(mob); ExMovimentacao ultMovNaoCanc = mob.getUltimaMovimentacaoNaoCancelada(); Boolean isDocumentoSemEfeito = mob.doc().isSemEfeito(); if (mob.isGeral()) { if (!mob.doc().isFinalizado()) { acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_ELABORACAO, mob.doc().getDtRegDoc(), mob.doc().getCadastrante(), mob.doc().getLotaCadastrante()); if (mob.getExDocumento().getSubscritor() != null) acrescentarMarca(set, mob, CpMarcador.MARCADOR_REVISAR, mob.doc().getDtRegDoc(), mob.getExDocumento().getSubscritor(), null); } if (mob.getExMovimentacaoSet() != null) { if (isDocumentoSemEfeito) { for (ExMovimentacao mov : mob.getExMovimentacaoSet()) { if (mov.isCancelada()) continue; Long t = mov.getIdTpMov(); if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TORNAR_SEM_EFEITO) { acrescentarMarca(set, mob, CpMarcador.MARCADOR_SEM_EFEITO, mov.getDtIniMov(), mov.getCadastrante(), mov.getLotaCadastrante()); } } } else { Long mDje = null; ExMovimentacao movDje = null; for (ExMovimentacao mov : mob.getExMovimentacaoSet()) { if (mov.isCancelada()) continue; Long m = null; Long t = mov.getIdTpMov(); if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PENDENCIA_DE_ANEXACAO) { acrescentarMarca(set, mob, CpMarcador.MARCADOR_PENDENTE_DE_ANEXACAO, mov.getDtIniMov(), mov.getCadastrante(), mov.getLotaCadastrante()); } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_VINCULACAO_PAPEL) { DpLotacao lotaPerfil = null; switch ((int) (long) mov.getExPapel().getIdPapel()) { case (int) ExPapel.PAPEL_GESTOR: m = CpMarcador.MARCADOR_COMO_GESTOR; break; case (int) ExPapel.PAPEL_INTERESSADO: m = CpMarcador.MARCADOR_COMO_INTERESSADO; break; } if (m != null && !mob.doc().isEliminado() && !mob.doc().isArquivadoPermanente()) { if (mov.getSubscritor() != null) /* perfil foi cadastrado para a pessoa */ lotaPerfil = null; else lotaPerfil = mov.getLotaSubscritor(); acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getSubscritor(), lotaPerfil); } } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PEDIDO_PUBLICACAO) { mDje = CpMarcador.MARCADOR_PUBLICACAO_SOLICITADA; movDje = mov; } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO) { mDje = CpMarcador.MARCADOR_REMETIDO_PARA_PUBLICACAO; movDje = mov; } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DISPONIBILIZACAO) { mDje = CpMarcador.MARCADOR_DISPONIBILIZADO; movDje = mov; } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ANEXACAO && mob.doc().isEletronico() && !mob.doc().jaTransferido()) { m = CpMarcador.MARCADOR_ANEXO_PENDENTE_DE_ASSINATURA; /* * no possvel usar ExMovimentacao.isAssinada() * pois no h tempo habil no BD de efetivar a * inclusao de movimentacao de assinatura de * movimento Edson: Por que no? */ for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) { if ((movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA) && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) { m = null; break; } } if (m != null) acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getCadastrante(), mov.getLotaCadastrante()); } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_INCLUSAO_DE_COSIGNATARIO) { if (mob.getDoc().isEletronico()) { if (!mob.getDoc().isAssinado()) m = CpMarcador.MARCADOR_REVISAR; else { if (mob.getDoc().isAssinadoSubscritor()) m = CpMarcador.MARCADOR_COMO_SUBSCRITOR; else m = CpMarcador.MARCADOR_REVISAR; for (ExMovimentacao assinatura : mob.getDoc().getTodasAsAssinaturas()) { if (assinatura.getSubscritor().equivale(mov.getSubscritor())) { m = null; break; } } } if (m != null) acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getSubscritor(), null); } } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_COM_SENHA) { boolean jaAutenticado = false; for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) { if (movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_DOCUMENTO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO) { jaAutenticado = true; break; } } if (!jaAutenticado) acrescentarMarca(set, mob, CpMarcador.MARCADOR_DOCUMENTO_ASSINADO_COM_SENHA, mov.getDtIniMov(), mov.getSubscritor(), null); } } if (mDje != null && !mob.doc().isEliminado()) { acrescentarMarca(set, mob, mDje, movDje.getDtIniMov(), movDje.getTitular(), movDje.getLotaTitular()); } } } return set; } else if (ultMovNaoCanc == null) { ExMovimentacao ultMov = mob.getUltimaMovimentacao(); Date dt = null; if (ultMov != null) { dt = ultMov.getDtIniMov(); } acrescentarMarca(set, mob, CpMarcador.MARCADOR_CANCELADO, dt, mob.doc().getCadastrante(), mob.doc().getLotaCadastrante()); return set; } if (!isDocumentoSemEfeito) { boolean apensadoAVolumeDoMesmoProcesso = mob.isApensadoAVolumeDoMesmoProcesso(); long m = CpMarcador.MARCADOR_CANCELADO; long m_aDevolverFora = CpMarcador.MARCADOR_A_DEVOLVER_FORA_DO_PRAZO; long m_aDevolver = CpMarcador.MARCADOR_A_DEVOLVER; long m_aguardando = CpMarcador.MARCADOR_AGUARDANDO; long m_aguardandoFora = CpMarcador.MARCADOR_AGUARDANDO_DEVOLUCAO_FORA_DO_PRAZO; long mAnterior = m; Date dt = null; //ExMovimentacao movT = new ExMovimentacao(); Set<ExMovimentacao> movT = new TreeSet<ExMovimentacao>(); //contemDataRetorno = false; for (ExMovimentacao mov : mob.getExMovimentacaoSet()) { if (mov.isCancelada()) continue; Long t = mov.getIdTpMov(); if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PENDENCIA_DE_ANEXACAO) m = CpMarcador.MARCADOR_PENDENTE_DE_ANEXACAO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PEDIDO_PUBLICACAO) m = CpMarcador.MARCADOR_PUBLICACAO_SOLICITADA; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DISPONIBILIZACAO) m = CpMarcador.MARCADOR_DISPONIBILIZADO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO) m = CpMarcador.MARCADOR_REMETIDO_PARA_PUBLICACAO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_SOBRESTAR) m = CpMarcador.MARCADOR_SOBRESTADO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA) m = CpMarcador.MARCADOR_JUNTADO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA_EXTERNO) m = CpMarcador.MARCADOR_JUNTADO_EXTERNO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_APENSACAO && apensadoAVolumeDoMesmoProcesso) m = CpMarcador.MARCADOR_APENSADO; if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA_EXTERNA || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA_EXTERNA) { m = CpMarcador.MARCADOR_TRANSFERIDO_A_ORGAO_EXTERNO; transferenciasSet.add(mov); if (mov.getDtFimMov() != null) { movT.add(mov); } } if ((t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA) && !apensadoAVolumeDoMesmoProcesso) { m = CpMarcador.MARCADOR_CAIXA_DE_ENTRADA; transferenciasSet.add(mov); if (mov.getDtFimMov() != null) { movT.add(mov); } } if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO && mob.doc().isEletronico()) { m = CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA; for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) { if ((movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA) && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) { m = mAnterior; } } } if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CRIACAO || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_RECEBIMENTO || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESOBRESTAR || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_DOCUMENTO || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_COM_SENHA || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CANCELAMENTO_JUNTADA || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESAPENSACAO) if (mob.doc().isAssinado() || mob.doc().getExTipoDocumento().getIdTpDoc() == 2 || mob.doc().getExTipoDocumento().getIdTpDoc() == 3) { if (!apensadoAVolumeDoMesmoProcesso) { m = CpMarcador.MARCADOR_EM_ANDAMENTO; } else m = CpMarcador.MARCADOR_APENSADO; } else if (mob.isApensado()) { m = CpMarcador.MARCADOR_APENSADO; } else { m = CpMarcador.MARCADOR_PENDENTE_DE_ASSINATURA; } if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ANEXACAO && mob.doc().isEletronico()) { m = CpMarcador.MARCADOR_ANEXO_PENDENTE_DE_ASSINATURA; /* * no possvel usar ExMovimentacao.isAssinada() pois no * h tempo habil no BD de efetivar a inclusao de * movimentacao de assinatura de movimento */ for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) { if ((movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA || movAss.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA) && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) { m = mAnterior; break; } } } if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA) { acrescentarMarca(set, mob, CpMarcador.MARCADOR_MOVIMENTACAO_ASSINADA_COM_SENHA, dt, mov.getSubscritor(), null); } if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA) { acrescentarMarca(set, mob, CpMarcador.MARCADOR_MOVIMENTACAO_CONFERIDA_COM_SENHA, dt, mov.getSubscritor(), null); } if (m != mAnterior) { dt = mov.getDtIniMov(); mAnterior = m; } } Iterator itr = movT.iterator(); while (itr.hasNext()) { ExMovimentacao element = (ExMovimentacao) itr.next(); if (element.getLotaCadastrante() != null && !transferenciasSet.isEmpty() && !contemRetornoTransferencia(element)) { Date dtMarca = element.getDtFimMov(); dtMarca.setHours(23); dtMarca.setMinutes(59); dtMarca.setSeconds(59); acrescentarMarcaTransferencia(set, mob, m_aguardando, dt, dtMarca, element.getCadastrante(), element.getLotaCadastrante()); // acrescenta a // marca // "Aguardando Devoluo" acrescentarMarcaTransferencia(set, mob, m_aDevolver, dt, dtMarca, element.getResp(), element.getLotaResp());// acrescenta a marca // "A Devolver" acrescentarMarcaTransferencia(set, mob, m_aguardandoFora, dtMarca, null, element.getCadastrante(), element.getLotaCadastrante()); // acrescenta a // marca // "Aguardando Devoluo (Fora do Prazo)" acrescentarMarcaTransferencia(set, mob, m_aDevolverFora, dtMarca, null, element.getResp(), element.getLotaResp());// acrescenta // a // marca // "A Devolver (Fora do Prazo)" } } if (m == CpMarcador.MARCADOR_PENDENTE_DE_ASSINATURA) { if (!mob.getDoc().isAssinadoSubscritor()) acrescentarMarca(set, mob, CpMarcador.MARCADOR_COMO_SUBSCRITOR, dt, mob.getExDocumento().getSubscritor(), null); } if (m == CpMarcador.MARCADOR_CAIXA_DE_ENTRADA) { if (!mob.doc().isEletronico()) { m = CpMarcador.MARCADOR_A_RECEBER; acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_TRANSITO, dt, ultMovNaoCanc.getCadastrante(), ultMovNaoCanc.getLotaCadastrante()); } else { if (ultMovNaoCanc.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA) { m = CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA; } else { acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_TRANSITO_ELETRONICO, dt, ultMovNaoCanc.getCadastrante(), ultMovNaoCanc.getLotaCadastrante()); } } } if (m == CpMarcador.MARCADOR_TRANSFERIDO_A_ORGAO_EXTERNO) { acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getCadastrante(), ultMovNaoCanc.getLotaCadastrante()); } else if (m == CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA) { if (ultMovNaoCanc.getCadastrante().getId() != ultMovNaoCanc.getSubscritor().getId()) { if (ultMovNaoCanc.getLotaCadastrante().getIdLotacao() != ultMovNaoCanc.getLotaSubscritor() .getIdLotacao()) { acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getSubscritor(), ultMovNaoCanc.getLotaSubscritor()); } else { acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getSubscritor(), null); } } acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getCadastrante(), ultMovNaoCanc.getLotaCadastrante()); } else if (m == CpMarcador.MARCADOR_JUNTADO || m == CpMarcador.MARCADOR_APENSADO) { if (!mob.isEliminado()) acrescentarMarca(set, mob, m, dt, null, null); } else { // Edson: Os marcadores "Arq Corrente" e // "Aguardando andamento" so mutuamente exclusivos if (m != CpMarcador.MARCADOR_EM_ANDAMENTO || !(mob.isArquivado() || mob.doc().getMobilGeral().isArquivado())) acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getResp(), ultMovNaoCanc.getLotaResp()); } } return set; }
From source file:org.apache.lens.server.metastore.TestMetastoreService.java
@Test(dataProvider = "mediaTypeData") public void testCreateFactTableWithMultipleUpdatePeriods(MediaType mediaType) throws Exception { final String table = "testCreateFactTableWithMultipleUpdatePeriods"; String prevDb = getCurrentDatabase(mediaType); final String DB = dbPFX + "testCreateFactTableWithMultipleUpdatePeriods_DB" + mediaType.getSubtype(); createDatabase(DB, mediaType);/*from w ww .ja v a 2s . c o m*/ setCurrentDatabase(DB, mediaType); createStorage("S1", mediaType); try { final XCube cube = createTestCube("testCube"); target().path("metastore").path("cubes").queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XCube>>(cubeObjectFactory.createXCube(cube)) { }, mediaType), APIResult.class); XFactTable f = createFactTable(table); String[] tables = new String[] { "testTable1", "testTable2", "testTable3" }; String[] updatePeriods = new String[] { "HOURLY", "DAILY", "MONTHLY" }; f.getStorageTables().getStorageTable() .add(createStorageTblWithMultipleTableDescriptors("S1", tables, updatePeriods)); APIResult result = target().path("metastore").path("facts").queryParam("sessionid", lensSessionId) .request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(f)) { }, mediaType), APIResult.class); assertSuccess(result); StringList factNames = target().path("metastore/facts").queryParam("sessionid", lensSessionId) .request(mediaType).get(StringList.class); assertTrue(factNames.getElements().contains(table.toLowerCase())); // Get the created tables JAXBElement<XFact> gotFactElement = target().path("metastore/facts").path(table) .queryParam("sessionid", lensSessionId).request(mediaType) .get(new GenericType<JAXBElement<XFact>>() { }); XFactTable gotFact = (XFactTable) gotFactElement.getValue(); assertTrue(gotFact.getName().equalsIgnoreCase(table)); assertEquals(gotFact.getWeight(), 10.0); // Check for the created tables per update period. List<XUpdatePeriodTableDescriptor> updatePeriodTableDescriptor = gotFact.getStorageTables() .getStorageTable().get(0).getUpdatePeriods().getUpdatePeriodTableDescriptor(); assertEquals(updatePeriodTableDescriptor.size(), 3); CubeFactTable cf = JAXBUtils.cubeFactFromFactTable(gotFact); Map<UpdatePeriod, String> updatePeriodTablePrefixMap = cf.getStoragePrefixUpdatePeriodMap().get("S1"); for (Map.Entry entry : updatePeriodTablePrefixMap.entrySet()) { assertEquals(entry.getValue(), entry.getKey() + "_S1"); } // Do some changes to test update cf.alterWeight(20.0); cf.alterColumn(new FieldSchema("c2", "double", "changed to double")); XFactTable update = JAXBUtils.factTableFromCubeFactTable(cf); XStorageTableElement s1Tbl = createStorageTblWithMultipleTableDescriptors("S1", new String[] { tables[0], tables[1] }, new String[] { updatePeriods[0], updatePeriods[1] }); update.getStorageTables().getStorageTable().add(s1Tbl); // Update result = target().path("metastore").path("facts").path(table).queryParam("sessionid", lensSessionId) .request(mediaType).put(Entity .entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(update)) { }, mediaType), APIResult.class); assertSuccess(result); // Get the updated table gotFactElement = target().path("metastore/facts").path(table).queryParam("sessionid", lensSessionId) .request(mediaType).get(new GenericType<JAXBElement<XFact>>() { }); gotFact = (XFactTable) gotFactElement.getValue(); CubeFactTable ucf = JAXBUtils.cubeFactFromFactTable(gotFact); assertEquals(ucf.weight(), 20.0); assertTrue(ucf.getUpdatePeriods().get("S1").contains(HOURLY)); assertTrue(ucf.getUpdatePeriods().get("S1").contains(DAILY)); assertFalse(ucf.getUpdatePeriods().get("S1").contains(MONTHLY)); // Add partitions final Date partDate = new Date(); XPartition xp = createPartition(table, partDate); APIResult partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertSuccess(partAddResult); // add same should fail partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertEquals(partAddResult.getStatus(), Status.FAILED); xp.setLocation(xp.getLocation() + "/a/b/c"); APIResult partUpdateResult = target().path("metastore/facts/").path(table).path("storages/S1/partition") .queryParam("sessionid", lensSessionId).request(mediaType).put(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertSuccess(partUpdateResult); JAXBElement<XPartitionList> partitionsElement = target().path("metastore/facts").path(table) .path("storages/S1/partitions").queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); //Getting partitions without filter will throw an error. Response res = target().path("metastore/facts").path(table).path("storages/S1/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).get(); assertEquals(res.getStatus(), 400); assertEquals(res.readEntity(String.class), "Partition filter can not be null or empty"); XPartitionList partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 1); XPartition readPartition = partitions.getPartition().get(0); assertEquals(readPartition.getLocation(), xp.getLocation()); assertEquals(readPartition.getTimePartitionSpec(), xp.getTimePartitionSpec()); assertEquals(readPartition.getNonTimePartitionSpec(), xp.getNonTimePartitionSpec()); assertNotNull(readPartition.getFullPartitionSpec()); XTimePartSpecElement timePartSpec = readPartition.getTimePartitionSpec().getPartSpecElement().iterator() .next(); XPartSpecElement fullPartSpec = readPartition.getFullPartitionSpec().getPartSpecElement().iterator() .next(); assertEquals(timePartSpec.getKey(), fullPartSpec.getKey()); assertEquals(UpdatePeriod.valueOf(xp.getUpdatePeriod().name()) .format(JAXBUtils.getDateFromXML(timePartSpec.getValue())), fullPartSpec.getValue()); DateTime date = target().path("metastore/cubes").path("testCube").path("latestdate") .queryParam("timeDimension", "dt").queryParam("sessionid", lensSessionId).request(mediaType) .get(DateTime.class); partDate.setMinutes(0); partDate.setSeconds(0); partDate.setTime(partDate.getTime() - partDate.getTime() % 1000); assertEquals(date.getDate(), partDate); // add two partitions, one of them already added. result should be partial XPartitionList parts = new XPartitionList(); parts.getPartition().add(xp); parts.getPartition().add(createPartition(table, DateUtils.addHours(partDate, 1))); partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partitions") .queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>( cubeObjectFactory.createXPartitionList(parts)) { }, mediaType), APIResult.class); assertEquals(partAddResult.getStatus(), Status.PARTIAL); // Drop the partitions APIResult dropResult = target().path("metastore/facts").path(table).path("storages/S1/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class); assertSuccess(dropResult); // Verify partition was dropped partitionsElement = target().path("metastore/facts").path(table).path("storages/S1/partitions") .queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 0); // add null in batch Response resp = target().path("metastore/facts/").path(table).path("storages/S1/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).post(null); Assert.assertEquals(resp.getStatus(), 400); // Drop the cube WebTarget target = target().path("metastore").path("cubes").path("testCube"); result = target.queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class); assertSuccess(result); } finally { setCurrentDatabase(prevDb, mediaType); dropDatabase(DB, mediaType); } }
From source file:org.apache.lens.server.metastore.TestMetastoreService.java
@SuppressWarnings("deprecation") @Test(dataProvider = "mediaTypeData") public void testFactStoragePartitions(MediaType mediaType) throws Exception { final String table = "testFactStoragePartitions"; final String DB = dbPFX + "testFactStoragePartitions_DB" + mediaType.getSubtype(); String prevDb = getCurrentDatabase(mediaType); createDatabase(DB, mediaType);//from w ww. j ava2 s . c o m setCurrentDatabase(DB, mediaType); createStorage("S1", mediaType); createStorage("S2", mediaType); try { final XCube cube = createTestCube("testCube"); target().path("metastore").path("cubes").queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XCube>>(cubeObjectFactory.createXCube(cube)) { }, mediaType), APIResult.class); XFactTable f = createFactTable(table); f.getStorageTables().getStorageTable().add(createStorageTblElement("S1", table, "HOURLY")); f.getStorageTables().getStorageTable().add(createStorageTblElement("S2", table, "DAILY")); f.getStorageTables().getStorageTable().add(createStorageTblElement("S2", table, "HOURLY")); APIResult result = target().path("metastore").path("facts").queryParam("sessionid", lensSessionId) .request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(f)) { }, mediaType), APIResult.class); assertSuccess(result); APIResult partAddResult; // Add null partition Response resp = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(null); Assert.assertEquals(resp.getStatus(), 400); // Add wrong partition final Date partDate = new Date(); XPartition xp2 = createPartition(table, partDate); xp2.getTimePartitionSpec().getPartSpecElement() .add(createTimePartSpecElement(partDate, "non_existant_time_part")); Response response = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp2)) { }, mediaType)); assertEquals(response.getStatus(), 400); partAddResult = response.readEntity(APIResult.class); assertEquals(partAddResult.getStatus(), Status.FAILED); assertEquals(partAddResult.getMessage(), "No timeline found for fact=testFactStoragePartitions, storage=S2, " + "update period=HOURLY, partition column=non_existant_time_part."); // Add a partition XPartition xp = createPartition(table, partDate); partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertSuccess(partAddResult); // add same should fail partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertEquals(partAddResult.getStatus(), Status.FAILED); xp.setLocation(xp.getLocation() + "/a/b/c"); APIResult partUpdateResult = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .put(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType), APIResult.class); assertSuccess(partUpdateResult); JAXBElement<XPartitionList> partitionsElement = target().path("metastore/facts").path(table) .path("storages/S2/partitions").queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); XPartitionList partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 1); XPartition readPartition = partitions.getPartition().get(0); assertEquals(readPartition.getLocation(), xp.getLocation()); assertEquals(readPartition.getTimePartitionSpec(), xp.getTimePartitionSpec()); assertEquals(readPartition.getNonTimePartitionSpec(), xp.getNonTimePartitionSpec()); assertNotNull(readPartition.getFullPartitionSpec()); XTimePartSpecElement timePartSpec = readPartition.getTimePartitionSpec().getPartSpecElement().iterator() .next(); XPartSpecElement fullPartSpec = readPartition.getFullPartitionSpec().getPartSpecElement().iterator() .next(); assertEquals(timePartSpec.getKey(), fullPartSpec.getKey()); assertEquals(UpdatePeriod.valueOf(xp.getUpdatePeriod().name()) .format(JAXBUtils.getDateFromXML(timePartSpec.getValue())), fullPartSpec.getValue()); DateTime date = target().path("metastore/cubes").path("testCube").path("latestdate") .queryParam("timeDimension", "dt").queryParam("sessionid", lensSessionId).request(mediaType) .get(DateTime.class); partDate.setMinutes(0); partDate.setSeconds(0); partDate.setTime(partDate.getTime() - partDate.getTime() % 1000); assertEquals(date.getDate(), partDate); // add two partitions, one of them already added. result should be partial XPartitionList parts = new XPartitionList(); parts.getPartition().add(xp); parts.getPartition().add(createPartition(table, DateUtils.addHours(partDate, 1))); partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>( cubeObjectFactory.createXPartitionList(parts)) { }, mediaType), APIResult.class); assertEquals(partAddResult.getStatus(), Status.PARTIAL); // Drop the partitions APIResult dropResult = target().path("metastore/facts").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class); assertSuccess(dropResult); // Verify partition was dropped partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 0); // add null in batch resp = target().path("metastore/facts/").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).post(null); Assert.assertEquals(resp.getStatus(), 400); // Try adding in batch, but to a wrong endpoint resp = target().path("metastore/facts/").path(table).path("storages/S2/partition") .queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>( cubeObjectFactory.createXPartitionList(toXPartitionList(xp))) { }, mediaType)); assertXMLError(resp, mediaType); // Try adding in batch, but provide just an XPartition resp = target().path("metastore/facts/").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity( new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) { }, mediaType)); if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) { assertXMLError(resp, mediaType); } else { // for json input, XPartitionList is getting created assertEquals(resp.getStatus(), 200); } // Try adding in batch with one partition being wrong wrt partition column. response = target().path("metastore/facts/").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>( cubeObjectFactory.createXPartitionList(toXPartitionList(xp2))) { }, mediaType)); assertEquals(response.getStatus(), 400); partAddResult = response.readEntity(APIResult.class); assertEquals(partAddResult.getStatus(), Status.FAILED); assertEquals(partAddResult.getMessage(), "No timeline found for fact=testFactStoragePartitions, storage=S2, " + "update period=HOURLY, partition column=non_existant_time_part."); // Add in batch partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId).request(mediaType) .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>( cubeObjectFactory.createXPartitionList(toXPartitionList(xp))) { }, mediaType), APIResult.class); assertSuccess(partAddResult); // Verify partition was added partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 1); // Drop again by values String[] val = new String[] { HOURLY.format(partDate) }; dropResult = target().path("metastore/facts").path(table).path("storages/S2/partition") .queryParam("values", StringUtils.join(val, ",")).queryParam("sessionid", lensSessionId) .request(mediaType).delete(APIResult.class); assertSuccess(dropResult); // Verify partition was dropped partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions") .queryParam("sessionid", lensSessionId) .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType) .get(new GenericType<JAXBElement<XPartitionList>>() { }); partitions = partitionsElement.getValue(); assertNotNull(partitions); assertEquals(partitions.getPartition().size(), 0); } finally { setCurrentDatabase(prevDb, mediaType); dropDatabase(DB, mediaType); } }