List of usage examples for java.lang Long intValue
public int intValue()
From source file:com.clustercontrol.hub.session.FluentdTransferFactory.java
/** * ?????????/*from www. j a va 2s.c o m*/ * */ @Override public Transfer createTansfer(final TransferInfo info, final PropertyBinder binder) throws TransferException { // HTTP ????? TransferDestProp urlProp = null; TransferDestProp connectTimeoutProp = null; TransferDestProp requestTimeoutProp = null; for (TransferDestProp prop : info.getDestProps()) { switch (prop.getName()) { case prop_url: urlProp = prop; break; case prop_connect_timeout: connectTimeoutProp = prop; break; case prop_request_timeout: requestTimeoutProp = prop; break; default: logger.warn(String.format("createTansfer() : unknown property(%s)", prop.getValue())); break; } } if (urlProp == null || urlProp.getValue() == null) throw new TransferException(String.format("createTansfer() : Value of \"%s\" must be set.", prop_url)); if (!urlPattern.matcher(urlProp.getValue()).matches()) throw new TransferException( String.format("createTansfer() : invalid url format. url=%s", urlProp.getValue())); final String urlStr = urlProp.getValue(); Integer timeout; try { timeout = Integer.valueOf(connectTimeoutProp.getValue()); } catch (NumberFormatException e) { timeout = DEFAULT_CONNECT_TIMEOUT; logger.warn(String.format("createTansfer() : can't regognize connectTimeout(%s) as number.", connectTimeoutProp.getValue())); } catch (NullPointerException e) { timeout = DEFAULT_CONNECT_TIMEOUT; logger.warn(String.format( "createTansfer() : connectTimeout is null, then use default value as connectTimeout(%s).", timeout)); } final Integer connectTimeout = timeout; try { timeout = Integer.valueOf(requestTimeoutProp.getValue()); } catch (NumberFormatException e) { timeout = DEFAULT_REQUEST_TIMEOUT; logger.warn(String.format("createTansfer() : can't regognize requestTimeout(%s) as number.", requestTimeoutProp.getValue())); } catch (NullPointerException e) { timeout = DEFAULT_CONNECT_TIMEOUT; logger.warn(String.format( "createTansfer() : requestTimeout is null, then use default value as requestTimeout(%s).", timeout)); } final Integer requestTimeout = timeout; // ?? return new Transfer() { private static final int BUFF_SIZE = 1024 * 1024; private static final int BODY_MAX_SIZE = 5 * BUFF_SIZE; private CloseableHttpClient client = null; /* * ?? * */ @Override public TransferNumericData transferNumerics(Iterable<TransferNumericData> numerics, TrasferCallback<TransferNumericData> callback) throws TransferException { TransferNumericData lastPosition = null; for (TransferNumericData numeric : numerics) { ObjectNode root = JsonNodeFactory.instance.objectNode(); root.put("item_name", numeric.key.getItemName()); root.put("display_name", numeric.key.getDisplayName()); root.put("monitor_id", numeric.key.getMonitorId()); root.put("facility_id", numeric.key.getFacilityid()); root.put("time", numeric.data.getTime()); root.put("value", numeric.data.getValue()); root.put("position", numeric.data.getPosition()); String url = binder.bind(numeric.key, numeric.data, urlStr); String data = root.toString(); try { send(url, data); lastPosition = numeric; if (callback != null) callback.onTransferred(lastPosition); } catch (Exception e) { logger.warn(e.getMessage(), e); internalError_monitor(numeric.key.getMonitorId(), data, e, url); break; } } return lastPosition; } /* * ?? * */ @Override public TransferStringData transferStrings(Iterable<TransferStringData> strings, TrasferCallback<TransferStringData> callback) throws TransferException { TransferStringData lastPosition = null; for (TransferStringData string : strings) { ObjectNode root = JsonNodeFactory.instance.objectNode(); root.put("target_name", string.key.getTargetName()); root.put("monitor_id", string.key.getMonitorId()); root.put("facility_id", string.key.getFacilityId()); root.put("log_format_id", string.data.getLogformatId()); root.put("time", string.data.getTime()); root.put("source", string.data.getValue()); for (CollectDataTag t : string.data.getTagList()) { root.put(t.getKey(), t.getValue()); } root.put("position", string.data.getDataId()); String url = binder.bind(string.key, string.data, urlStr); String data = root.toString(); try { send(url, data); lastPosition = string; if (callback != null) callback.onTransferred(lastPosition); } catch (Exception e) { logger.warn(e.getMessage(), e); internalError_monitor(string.key.getMonitorId(), data, e, url); break; } } return lastPosition; } /* * ?? * */ @Override public JobSessionEntity transferJobs(Iterable<JobSessionEntity> sessions, TrasferCallback<JobSessionEntity> callback) throws TransferException { JobSessionEntity lastPosition = null; for (JobSessionEntity session : sessions) { ObjectNode sessionNode = JsonNodeFactory.instance.objectNode(); sessionNode.put("ssession_id", session.getSessionId()); sessionNode.put("job_id", session.getJobId()); sessionNode.put("jobunit_id", session.getJobunitId()); sessionNode.put("schedule_date", session.getScheduleDate()); sessionNode.put("position", session.getPosition()); ArrayNode jobArray = sessionNode.putArray("jobs"); for (JobSessionJobEntity job : session.getJobSessionJobEntities()) { ObjectNode jobNode = jobArray.addObject(); jobNode.put("job_id", job.getId().getJobId()); jobNode.put("jobunit_id", job.getId().getJobunitId()); if (job.getScopeText() != null) jobNode.put("scope_text", job.getScopeText()); if (job.getStatus() != null) jobNode.put("status", job.getStatus()); if (job.getStartDate() != null) jobNode.put("start_date", job.getStartDate()); if (job.getEndDate() != null) jobNode.put("end_date", job.getEndDate()); if (job.getEndValue() != null) jobNode.put("end_value", job.getEndValue()); if (job.getEndStatus() != null) jobNode.put("end_status", job.getEndStatus()); if (job.getResult() != null) jobNode.put("result", job.getResult()); if (job.getJobInfoEntity() != null) jobNode.put("job_type", job.getJobInfoEntity().getJobType()); if (!job.getJobSessionNodeEntities().isEmpty()) { ArrayNode nodeArray = jobNode.putArray("nodes"); for (JobSessionNodeEntity node : job.getJobSessionNodeEntities()) { ObjectNode nodeNode = nodeArray.addObject(); nodeNode.put("facility_id", node.getId().getFacilityId()); nodeNode.put("node_name", node.getNodeName()); nodeNode.put("status", node.getStatus()); nodeNode.put("start_date", node.getStartDate()); nodeNode.put("end_date", node.getEndDate()); nodeNode.put("end_value", node.getEndValue()); nodeNode.put("message", node.getMessage()); nodeNode.put("result", node.getResult()); nodeNode.put("start_date", node.getStartDate()); nodeNode.put("startup_time", node.getStartupTime()); nodeNode.put("instance_id", node.getInstanceId()); } } } String url = binder.bind(session, urlStr); String data = sessionNode.toString(); try { send(url, data); lastPosition = session; if (callback != null) callback.onTransferred(lastPosition); } catch (Exception e) { logger.warn(e.getMessage(), e); internalError_session(session.getSessionId(), data, e, url); break; } } return lastPosition; } /* * ?? * */ @Override public EventLogEntity transferEvents(Iterable<EventLogEntity> events, TrasferCallback<EventLogEntity> callback) throws TransferException { EventLogEntity lastPosition = null; for (EventLogEntity event : events) { ObjectNode eventNode = JsonNodeFactory.instance.objectNode(); eventNode.put("monitor_id", event.getId().getMonitorId()); eventNode.put("monitor_detail_id", event.getId().getMonitorDetailId()); eventNode.put("plugin_id", event.getId().getPluginId()); eventNode.put("generation_date", event.getGenerationDate()); eventNode.put("facility_id", event.getId().getFacilityId()); eventNode.put("scope_text", event.getScopeText()); eventNode.put("application", event.getApplication()); eventNode.put("message", event.getMessage()); eventNode.put("message_org", event.getMessageOrg()); eventNode.put("priority", event.getPriority()); eventNode.put("confirm_flg", event.getConfirmFlg()); eventNode.put("confirm_date", event.getCommentDate()); eventNode.put("confirm_user", event.getCommentUser()); eventNode.put("duplication_count", event.getDuplicationCount()); eventNode.put("output_date", event.getId().getOutputDate()); eventNode.put("inhibited_flg", event.getInhibitedFlg()); eventNode.put("comment_date", event.getCommentDate()); eventNode.put("comment_user", event.getCommentUser()); eventNode.put("comment", event.getComment()); eventNode.put("position", event.getPosition()); String url = binder.bind(event, urlStr); String data = eventNode.toString(); try { send(url, data); lastPosition = event; if (callback != null) callback.onTransferred(lastPosition); } catch (Exception e) { logger.warn(e.getMessage(), e); internalError_monitor(event.getId().getMonitorId(), data, e, url); break; } } return lastPosition; } /* * ID ?? * */ @Override public String getDestTypeId() { return transfer_id; } /* * Fluentd ?????? HttpClient ?? * ????????? * */ private CloseableHttpClient getHttpClient() { if (client == null) { client = createHttpClient(); } return client; } /* * Fluentd ?????? HttpClient ?? * */ private CloseableHttpClient createHttpClient() { String proxyHost = null; Integer proxyPort = null; CredentialsProvider cledentialProvider = null; List<String> ignoreHostList = new ArrayList<>(); try { // Hinemos ??? proxyHost = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.host", null); Long proxyPortLong = HinemosPropertyUtil.getHinemosPropertyNum("hub.fluentd.proxy.port", null); if (proxyPortLong != null) proxyPort = proxyPortLong.intValue(); if (proxyPort == null) proxyPort = 80; String proxyUser = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.user", null); String proxyPassword = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.password", null); if (proxyHost != null && proxyPort != null) { logger.debug( "initializing fluentd proxy : proxyHost = " + proxyHost + ", port = " + proxyPort); String ignoreHostStr = HinemosPropertyUtil .getHinemosPropertyStr("hub.fluentd.proxy.ignorehosts", null); if (ignoreHostStr != null) { ignoreHostList = Arrays.asList(ignoreHostStr.split(",")); } if (proxyUser != null && proxyPassword != null) { cledentialProvider = new BasicCredentialsProvider(); cledentialProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } } catch (Throwable t) { logger.warn("invalid proxy configuration.", t); proxyHost = null; proxyPort = null; cledentialProvider = null; ignoreHostList = Collections.emptyList(); } List<Header> headers = new ArrayList<>(); HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(cledentialProvider) .setDefaultHeaders(headers); Builder requestBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT); if (connectTimeout != null) requestBuilder.setConnectTimeout(connectTimeout); if (connectTimeout != null) requestBuilder.setSocketTimeout(requestTimeout); builder.setDefaultRequestConfig(requestBuilder.build()); if (proxyHost != null) { Matcher m = urlPattern.matcher(urlStr); if (!m.matches()) throw new InternalError(String.format("invalid url(%s)", urlStr)); m.toMatchResult(); boolean ignore = false; String host = m.group("host"); for (String ignoreHost : ignoreHostList) { if (ignoreHost.equals(host)) { ignore = true; break; } } if (!ignore) { HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http"); builder.setProxy(proxy); } } if (keepAlive) { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); } else { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } return builder.build(); } /* * ?? URL ??? * */ private void send(String url, String data) throws Exception { // URL ? Matcher m = urlPattern.matcher(url); if (!m.matches()) throw new InternalError(String.format("invalid url(%s)", urlStr)); m.toMatchResult(); String path = m.group("path"); if (path != null && !path.isEmpty()) { String host = m.group("host"); String port = m.group("port"); String[] paths = path.split("/"); for (int i = 1; i < paths.length; ++i) { paths[i] = URLEncoder.encode(paths[i], "utf-8"); } url = "http://" + host + (port == null || port.isEmpty() ? "" : (":" + port)); for (int i = 1; i < paths.length; ++i) { url += "/" + paths[i]; } } HttpPost requestPost = new HttpPost(url); requestPost.addHeader("content-type", "application/json"); requestPost.setEntity(new StringEntity(data, StandardCharsets.UTF_8)); logger.debug(String.format("send() : request start. url=%s", url)); int count = 0; int maxTryCount = PropertyConstants.hub_transfer_max_try_count.number(); while (count < maxTryCount) { try { long start = HinemosTime.currentTimeMillis(); try (CloseableHttpResponse response = getHttpClient().execute(requestPost)) { long responseTime = HinemosTime.currentTimeMillis() - start; logger.debug(String.format("send() : url=%s, responseTime=%d", url, responseTime)); int statusCode = response.getStatusLine().getStatusCode(); logger.debug(String.format("send() : url=%s, code=%d", url, statusCode)); if (statusCode == HttpStatus.SC_OK) { logger.debug(String.format("send() : url=%s, success=%s", url, response.getStatusLine().toString())); if (logger.isDebugEnabled()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (InputStream in = response.getEntity().getContent()) { byte[] buffer = new byte[BUFF_SIZE]; while (out.size() < BODY_MAX_SIZE) { int len = in.read(buffer); if (len < 0) { break; } out.write(buffer, 0, len); } } String res = new String(out.toByteArray(), "UTF-8"); if (!res.isEmpty()) logger.debug(String.format("send() : url=%s, response=%s", url, res)); } } else { throw new RuntimeException( String.format("http status code isn't 200. code=%d, message=%s", statusCode, response.getStatusLine().toString())); } } logger.debug(String.format("send() : success. url=%s, count=%d", url, count)); break; } catch (RuntimeException e) { ++count; if (count < maxTryCount) { logger.debug(e.getMessage(), e); logger.debug(String.format( "send() : fail to send, and then wait to retry. url=%s, count=%d", url, count)); try { Thread.sleep(1000); } catch (InterruptedException e1) { logger.debug(e.getMessage()); } } else { throw new TransferException( String.format("send() : fail to send. url=%s, retry count=%d, error=\"%s\"", url, count, e.getMessage())); } } } } @Override public void close() throws Exception { if (client != null) client.close(); } private void internalError_session(String sessionId, String data, Exception error, String url) { internalError_session(sessionId, data, error.getMessage() == null || error.getMessage().isEmpty() ? error.getClass().getSimpleName() : error.getMessage(), url); } private void internalError_session(String sessionId, String data, String error, String url) { AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER, MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() }, String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nsessionId=%s%ndata=%s%nurl=%s", error, info.getTransferId(), info.getDestTypeId(), sessionId, data, url)); } private void internalError_monitor(String sessionId, String data, Exception error, String url) { internalError_monitor(sessionId, data, error.getMessage() == null || error.getMessage().isEmpty() ? error.getClass().getSimpleName() : error.getMessage(), url); } private void internalError_monitor(String monitorId, String data, String error, String url) { AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER, MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() }, String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nmonitorId=%s%ndata=%s%nurl=%s", error, info.getTransferId(), info.getDestTypeId(), monitorId, data, url)); } }; }
From source file:com.ibm.asset.trails.service.impl.ReconWorkspaceServiceImpl.java
private List<Long> filterTargetAffectedBreakAlertList4MachineLevel(AlertUnlicensedSw workingAlert, List<AlertUnlicensedSw> affectedAlertList4MachineLevel) { List<Long> targetAffectedBreakAlertList4MachineLevel = new ArrayList<Long>(); if (workingAlert != null && affectedAlertList4MachineLevel != null) { int workingAlertAccountId = workingAlert.getInstalledSoftware().getSoftwareLpar().getAccount().getId() .intValue();/*from w w w . j a v a2 s. c om*/ for (AlertUnlicensedSw affectedAlertObj : affectedAlertList4MachineLevel) { int affectedAlertAccountId = affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getAccount() .getId().intValue(); if (workingAlertAccountId == affectedAlertAccountId) {// Same // Acccount targetAffectedBreakAlertList4MachineLevel.add(affectedAlertObj.getId()); } else {// Cross Account ScheduleF scheduleF4WorkingAlert = vSwLparDAO.getScheduleFItem( workingAlert.getInstalledSoftware().getSoftwareLpar().getAccount(), workingAlert.getInstalledSoftware().getSoftware().getSoftwareName(), workingAlert.getInstalledSoftware().getSoftwareLpar().getName(), workingAlert.getInstalledSoftware().getSoftwareLpar().getHardwareLpar().getHardware() .getOwner(), workingAlert.getInstalledSoftware().getSoftwareLpar().getHardwareLpar().getHardware() .getMachineType().getName(), workingAlert.getInstalledSoftware().getSoftwareLpar().getHardwareLpar().getHardware() .getSerial(), workingAlert.getInstalledSoftware().getSoftware().getManufacturerId() .getManufacturerName()); ScheduleF scheduleF4AffectedAlert = vSwLparDAO.getScheduleFItem( affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getAccount(), affectedAlertObj.getInstalledSoftware().getSoftware().getSoftwareName(), affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getName(), affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getHardwareLpar() .getHardware().getOwner(), affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getHardwareLpar() .getHardware().getMachineType().getName(), affectedAlertObj.getInstalledSoftware().getSoftwareLpar().getHardwareLpar() .getHardware().getSerial(), affectedAlertObj.getInstalledSoftware().getSoftware().getManufacturerId() .getManufacturerName()); if (scheduleF4WorkingAlert != null && scheduleF4AffectedAlert != null) { Long scopeId4WorkingAlert = scheduleF4WorkingAlert.getScope().getId(); Long scopeId4AffecteddAlert = scheduleF4AffectedAlert.getScope().getId(); if (scopeId4WorkingAlert.intValue() == 3// Working Alert // Scope must be // IBM owned, // IBM managed && scheduleF4WorkingAlert.getLevel() != null && !scheduleF4WorkingAlert.getLevel().trim().equals("HOSTNAME")// Working Alert // Level must be // great than // "HOSTNAME"(The // value can be // 'HWBOX','HWOWNER','PRODUCT') && scopeId4AffecteddAlert.intValue() == 3// Cross // Account // Alert // Scope // must // be // IBM // owned, // IBM // managed && scheduleF4AffectedAlert.getLevel() != null && !scheduleF4AffectedAlert.getLevel().trim().equals("HOSTNAME")// Cross Account // Alert Level must // be great than // "HOSTNAME"(The // value can be // 'HWBOX','HWOWNER','PRODUCT') ) { targetAffectedBreakAlertList4MachineLevel.add(affectedAlertObj.getId()); } } } } } return targetAffectedBreakAlertList4MachineLevel; }
From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java
public CosemObjectDefinition readObjectDefinition(final DataObject resultData, final String description) throws ProtocolAdapterException { final List<DataObject> objectDefinitionElements = this.readList(resultData, description); if (objectDefinitionElements == null) { return null; }//ww w . ja va2 s .co m if (objectDefinitionElements.size() != 4) { LOGGER.error("Unexpected ResultData for Object Definition value: {}", this.getDebugInfo(resultData)); throw new ProtocolAdapterException("Expected list for Object Definition to contain 4 elements, got: " + objectDefinitionElements.size()); } final Long classId = this.readLongNotNull(objectDefinitionElements.get(0), "Class ID from " + description); final CosemObisCode logicalName = this.readLogicalName(objectDefinitionElements.get(1), "Logical Name from " + description); final Long attributeIndex = this.readLongNotNull(objectDefinitionElements.get(2), "Attribute Index from " + description); final Long dataIndex = this.readLongNotNull(objectDefinitionElements.get(0), "Data Index from " + description); return new CosemObjectDefinition(classId.intValue(), logicalName, attributeIndex.intValue(), dataIndex.intValue()); }
From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java
public QueryResult getPageAt(Integer rowIndex) throws EJBExceptionLP { QueryResult result = null;//from w w w . java2 s .c o m SessionFactory factory = FLRSessionFactory.getFactory(); Session session = null; Iterator resultListIterator = null; List resultList = null; try { int colCount = getTableInfo().getColumnClasses().length; int pageSize = getLimit(); int startIndex = Math.max(rowIndex.intValue() - (pageSize / 2), 0); int endIndex = startIndex + pageSize - 1; session = factory.openSession(); session = setFilter(session); String queryString = "SELECT artikelliste.i_id FROM FLRArtikelliste AS artikelliste " + " LEFT OUTER JOIN artikelliste.artikellagerset AS alager " + " LEFT OUTER JOIN artikelliste.flrgeometrie AS geo " + " LEFT OUTER JOIN artikelliste.artikellieferantset AS artikellieferantset " + " LEFT OUTER JOIN artikelliste.stuecklisten AS stuecklisten " + " LEFT OUTER JOIN artikelliste.artikelsprset AS aspr " + " LEFT OUTER JOIN artikelliste.flrartikelgruppe AS ag " + " LEFT OUTER JOIN artikelliste.flrartikelklasse AS ak " + this.buildWhereClause() + this.buildGroupByClause() + this.buildOrderByClause(); Query query = session.createQuery(queryString); query.setFirstResult(startIndex); query.setMaxResults(pageSize); resultList = query.list(); Object[][] rows = new Object[resultList.size()][colCount]; Integer[] iIds = new Integer[resultList.size()]; iIds = (Integer[]) resultList.toArray(iIds); String in = ""; String inArtikel_i_id = ""; HashMap hmRabattsatzFixpreis = new HashMap(); HashMap hmPreisbasis = new HashMap(); HashMap<Integer, String> hmKommentarTooltip = new HashMap<Integer, String>(); if (resultList.size() > 0) { in = " AND artikelliste.i_id IN("; inArtikel_i_id = " pl.artikel_i_id IN("; String inKommentar = " ko.artikelkommentar.artikel_i_id IN("; for (int i = 0; i < iIds.length; i++) { if (i == iIds.length - 1) { in += iIds[i]; inArtikel_i_id += iIds[i]; inKommentar += iIds[i]; } else { in += iIds[i] + ","; inArtikel_i_id += iIds[i] + ","; inKommentar += iIds[i] + ","; } } in += ") "; inArtikel_i_id += ") "; inKommentar += ") "; // String ins = StringUtils.join(iIds, ",") ; session.close(); session = factory.openSession(); session = setFilter(session); queryString = this.getFromClause() + this.buildWhereClause() + in + this.buildGroupByClause() + this.buildOrderByClause(); query = session.createQuery(queryString); resultList = query.list(); Session sessionVkPreisBasis = factory.openSession(); String rabattsatzFixpreis = "SELECT pl.artikel_i_id, pl.n_artikelstandardrabattsatz ,pl.n_artikelfixpreis FROM FLRVkpfartikelpreis AS pl WHERE pl.vkpfartikelpreisliste_i_id=" + vkPreisliste + " AND " + inArtikel_i_id + " ORDER BY t_preisgueltigab DESC "; Query queryRabattsatzFixpreis = sessionVkPreisBasis.createQuery(rabattsatzFixpreis); List resultListRabattsatzFixpreis = queryRabattsatzFixpreis.list(); Iterator resultListIteratorRabattsatzFixpreis = resultListRabattsatzFixpreis.iterator(); while (resultListIteratorRabattsatzFixpreis.hasNext()) { Object[] o = (Object[]) resultListIteratorRabattsatzFixpreis.next(); if (!hmRabattsatzFixpreis.containsKey(o[0])) { hmRabattsatzFixpreis.put(o[0], o); } } sessionVkPreisBasis.close(); sessionVkPreisBasis = factory.openSession(); String preisbasis; if (bVkPreisLief1preis) { preisbasis = "SELECT pl.artikel_i_id, pl.n_nettopreis FROM FLRArtikellieferant AS pl WHERE " + inArtikel_i_id + " ORDER BY i_sort ASC "; } else { preisbasis = "SELECT pl.artikel_i_id, pl.n_verkaufspreisbasis FROM FLRVkpfartikelverkaufspreisbasis AS pl WHERE " + inArtikel_i_id + " AND t_verkaufspreisbasisgueltigab <='" + Helper.formatDateWithSlashes(new java.sql.Date(System.currentTimeMillis())) + "'" + " ORDER BY t_verkaufspreisbasisgueltigab DESC "; } Query queryPreisbasis = sessionVkPreisBasis.createQuery(preisbasis); List resultListPreisbasis = queryPreisbasis.list(); Iterator resultListIteratorPreisbasis = resultListPreisbasis.iterator(); while (resultListIteratorPreisbasis.hasNext()) { Object[] o = (Object[]) resultListIteratorPreisbasis.next(); if (!hmPreisbasis.containsKey(o[0])) { hmPreisbasis.put(o[0], o[1]); } } sessionVkPreisBasis.close(); // PJ18025 sessionVkPreisBasis = factory.openSession(); String kommentare = "SELECT ko.artikelkommentar.artikel_i_id, ko.x_kommentar, ko.artikelkommentar.flrartikelkommentarart.c_nr FROM FLRArtikelkommentarspr AS ko WHERE " + inKommentar + " AND ko.locale='" + theClientDto.getLocUiAsString() + "' AND ko.artikelkommentar.flrartikelkommentarart.b_tooltip=1 "; Query queryKommentare = sessionVkPreisBasis.createQuery(kommentare); List resultListKommentare = queryKommentare.list(); Iterator resultListIteratorKommentare = resultListKommentare.iterator(); while (resultListIteratorKommentare.hasNext()) { Object[] o = (Object[]) resultListIteratorKommentare.next(); if (o[2] != null) { String kommentar = "<b>" + (String) o[2] + ":</b>\n" + (String) o[1]; String kommentarVorhanden = ""; if (hmKommentarTooltip.containsKey(o[0])) { kommentarVorhanden = hmKommentarTooltip.get(o[0]) + "<br><br>" + kommentar; } else { kommentarVorhanden = kommentar; } hmKommentarTooltip.put((Integer) o[0], kommentarVorhanden); } } sessionVkPreisBasis.close(); } rows = new Object[resultList.size()][colCount]; resultListIterator = resultList.iterator(); int row = 0; String[] tooltipData = new String[resultList.size()]; while (resultListIterator.hasNext()) { Object o[] = (Object[]) resultListIterator.next(); Object[] rowToAddCandidate = new Object[colCount]; rowToAddCandidate[getTableColumnInformation().getViewIndex("i_id")] = o[0]; rowToAddCandidate[getTableColumnInformation().getViewIndex("artikel.artikelnummerlang")] = o[1]; rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.stuecklistenart")] = o[13] != null ? ((String) o[13]).trim() : o[13]; if (bKurzbezeichnungAnzeigen) { prepareKurzbezeichnung(o, rowToAddCandidate); } rowToAddCandidate[getTableColumnInformation().getViewIndex("bes.artikelbezeichnung")] = o[2]; if (bAbmessungenStattZusatzbezeichnung || bArtikelgruppeStattZusatzbezeichnung) { if (bAbmessungenStattZusatzbezeichnung) { prepareAbmessungen(o, rowToAddCandidate); } else { prepareArtikelGruppeInAbmessung(o, rowToAddCandidate); } } else { rowToAddCandidate[getTableColumnInformation().getViewIndex("artikel.zusatzbez")] = o[6]; } if (bArtikelgruppeAnzeigen) { prepareArtikelGruppe(o, rowToAddCandidate); } else { if (bArtikelklasseAnzeigen) { prepareArtikelKlasse(o, rowToAddCandidate); } } if (bVkPreisStattGestpreis == true) { prepareVkPreis(hmRabattsatzFixpreis, hmPreisbasis, o, rowToAddCandidate); } if (o[4] != null && Helper.short2boolean((Short) o[5])) { rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.lagerstand")] = o[3]; } else { rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.lagerstand")] = new BigDecimal( 0); } if (bLagerplaetzeAnzeigen) { prepareLagerplaetze((Integer) o[0], rowToAddCandidate); } if (bDarfPreiseSehen) { // Gestehungspreis holen BigDecimal gestehungspreis = (BigDecimal) o[4]; if (gestehungspreis != null && ((BigDecimal) rowToAddCandidate[getTableColumnInformation() .getViewIndex("lp.lagerstand")]).doubleValue() > 0) { gestehungspreis = gestehungspreis.divide( new BigDecimal(((BigDecimal) rowToAddCandidate[getTableColumnInformation() .getViewIndex("lp.lagerstand")]).doubleValue()), 4, BigDecimal.ROUND_HALF_EVEN); } else { // Projekt 10870: WH: Wenn kein Gestpreis zustandekommt, // dann Gestpreis des Hauptlagers anzeigen if (Helper.short2boolean((Short) o[5]) && o[8] != null) { gestehungspreis = (BigDecimal) o[8]; } else { gestehungspreis = new BigDecimal(0); } } if (bVkPreisStattGestpreis == false) { rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.preis")] = gestehungspreis; } } else { rowToAddCandidate[getTableColumnInformation().getViewIndex("lp.preis")] = new BigDecimal(0); } Long lAnzahlReklamationen = (Long) o[15]; Boolean hatOffeneReklamationen = (lAnzahlReklamationen != null) && lAnzahlReklamationen.intValue() > 0; FLRArtikelsperren as = (FLRArtikelsperren) o[7]; if (as != null || hatOffeneReklamationen) { String gesperrt = null; if (as != null) { gesperrt = as.getFlrsperren().getC_bez(); } if (hatOffeneReklamationen) { rowToAddCandidate[getTableColumnInformation() .getViewIndex("Icon")] = getStatusMitUebersetzung(gesperrt, new java.sql.Timestamp(System.currentTimeMillis()), "R"); } else { rowToAddCandidate[getTableColumnInformation().getViewIndex("Icon")] = gesperrt; } } if (!Helper.short2boolean((Short) o[18])) { rowToAddCandidate[getTableColumnInformation().getViewIndex("Color")] = new Color(0, 0, 255); } rows[row] = rowToAddCandidate; // PJ18025 String tooltip = (String) hmKommentarTooltip.get(o[0]); if (tooltip != null) { String text = tooltip; text = text.replaceAll("\n", "<br>"); text = "<html>" + text + "</html>"; tooltipData[row] = text; } row++; } result = new QueryResult(rows, getRowCount(), startIndex, endIndex, 0, tooltipData); } catch (Exception e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e); } finally { closeSession(session); } return result; }
From source file:au.org.theark.lims.model.dao.InventoryDao.java
public BiospecimenLocationVO getInvCellLocation(InvCell invCell) throws ArkSystemException { BiospecimenLocationVO biospecimenLocationVo = new BiospecimenLocationVO(); StringBuilder hqlString = new StringBuilder(); hqlString.append(/*w ww . ja v a 2 s. c om*/ "SELECT site.name AS siteName, freezer.name as freezerName, rack.name AS rackName, box.name AS boxName, cell.colno AS column, cell.rowno AS row, box.colnotype.name AS colNoType, box.rownotype.name AS rowNoType \n"); hqlString.append("FROM InvCell AS cell \n"); hqlString.append("LEFT JOIN cell.invBox AS box \n"); hqlString.append("LEFT JOIN box.invRack AS rack \n"); hqlString.append("LEFT JOIN rack.invFreezer AS freezer \n"); hqlString.append("LEFT JOIN freezer.invSite AS site \n"); hqlString.append("WHERE cell.id = :id"); Query q = getSession().createQuery(hqlString.toString()); q.setParameter("id", invCell.getId()); Object[] result = (Object[]) q.uniqueResult(); if (result != null) { biospecimenLocationVo.setSiteName(result[0].toString()); biospecimenLocationVo.setFreezerName(result[1].toString()); biospecimenLocationVo.setRackName(result[2].toString()); biospecimenLocationVo.setBoxName(result[3].toString()); Long colno = new Long((Long) result[4]); Long rowno = new Long((Long) result[5]); biospecimenLocationVo.setColumn(colno); biospecimenLocationVo.setRow(rowno); String colNoType = result[6].toString(); String rowNoType = result[7].toString(); String colLabel = new String(); if (colNoType.equalsIgnoreCase("ALPHABET")) { char character = (char) (colno + 64); colLabel = new Character(character).toString(); } else { colLabel = new Integer(colno.intValue()).toString(); } biospecimenLocationVo.setColLabel(colLabel); String rowLabel = new String(); if (rowNoType.equalsIgnoreCase("ALPHABET")) { char character = (char) (rowno + 64); rowLabel = new Character(character).toString(); } else { rowLabel = new Integer(rowno.intValue()).toString(); } biospecimenLocationVo.setRowLabel(rowLabel); } return biospecimenLocationVo; }
From source file:au.org.theark.lims.model.dao.InventoryDao.java
public BiospecimenLocationVO getBiospecimenLocation(Biospecimen biospecimen) { BiospecimenLocationVO biospecimenLocationVo = new BiospecimenLocationVO(); StringBuilder hqlString = new StringBuilder(); hqlString.append(/*from w w w .ja v a 2 s . co m*/ "SELECT site.name AS siteName, freezer.name as freezerName, rack.name AS rackName, box.name AS boxName, cell.colno AS column, cell.rowno AS row, box.colnotype.name AS colNoType, box.rownotype.name AS rowNoType \n"); hqlString.append("FROM InvCell AS cell \n"); hqlString.append("LEFT JOIN cell.invBox AS box \n"); hqlString.append("LEFT JOIN box.invRack AS rack \n"); hqlString.append("LEFT JOIN rack.invFreezer AS freezer \n"); hqlString.append("LEFT JOIN freezer.invSite AS site \n"); hqlString.append("WHERE cell.biospecimen = :biospecimen"); Query q = getSession().createQuery(hqlString.toString()); q.setParameter("biospecimen", biospecimen); Object[] result = (Object[]) q.uniqueResult(); if (result != null) { biospecimenLocationVo.setIsAllocated(true); biospecimenLocationVo.setSiteName(result[0].toString()); biospecimenLocationVo.setFreezerName(result[1].toString()); biospecimenLocationVo.setRackName(result[2].toString()); biospecimenLocationVo.setBoxName(result[3].toString()); Long colno = new Long((Long) result[4]); Long rowno = new Long((Long) result[5]); biospecimenLocationVo.setColumn(colno); biospecimenLocationVo.setRow(rowno); String colNoType = result[6].toString(); String rowNoType = result[7].toString(); String colLabel = new String(); if (colNoType.equalsIgnoreCase("ALPHABET")) { char character = (char) (colno + 64); colLabel = new Character(character).toString(); } else { colLabel = new Integer(colno.intValue()).toString(); } biospecimenLocationVo.setColLabel(colLabel); String rowLabel = new String(); if (rowNoType.equalsIgnoreCase("ALPHABET")) { char character = (char) (rowno + 64); rowLabel = new Character(character).toString(); } else { rowLabel = new Integer(rowno.intValue()).toString(); } biospecimenLocationVo.setRowLabel(rowLabel); } return biospecimenLocationVo; }
From source file:br.org.indt.ndg.server.survey.SurveyHandlerBean.java
private Integer getQtResultsBySurvey(String idSurvey) throws MSMApplicationException { Query q = manager.createNamedQuery("result.getQtResultsBySurvey"); q.setParameter("IDSurvey", idSurvey); Long qt = (Long) q.getSingleResult(); return qt.intValue(); }
From source file:com.tmount.business.carhot.controller.CarHotInsertCarInfo.java
@Override protected void doService(RequestParam requestParam, JsonGenerator responseBodyJson) throws ShopException, JsonGenerationException, IOException { long account_id = ParamData.getLong(requestParam.getBodyNode(), "account_id"); //account_id String car_color = ParamData.getString(requestParam.getBodyNode(), "car_color"); // int car_type = ParamData.getInt(requestParam.getBodyNode(), "car_type"); // String car_plate_number = ParamData.getString(requestParam.getBodyNode(), "car_plate_number"); //? String car_carcase_num = ParamData.getString(requestParam.getBodyNode(), "car_carcase_num"); //? String car_engine_num = ParamData.getString(requestParam.getBodyNode(), "car_engine_num"); //?? String car_driving_license_date = ParamData.getString(requestParam.getBodyNode(), "car_driving_license_date"); // String city_code = ParamData.getString(requestParam.getBodyNode(), "city_code"); // CarInfo carinfo = new CarInfo(); carinfo.setAccount_id(account_id);// ww w. j a v a 2s.c om carinfo.setCar_color(car_color); carinfo.setCar_driving_license_date(car_driving_license_date); carinfo.setCar_type(car_type); carinfo.setCar_plate_number(car_plate_number); if (StringUtils.isNotBlank(car_carcase_num)) { carinfo.setCar_carcase_num(car_carcase_num); } if (StringUtils.isNotBlank(city_code)) { carinfo.setCity_code(city_code); } carinfo.setCar_engine_num(car_engine_num); Long user_id = userService.getUserMessage(account_id); //?account_iduser_id if (null != user_id) { List<CarInfo> carList = carInfoService.getCarInfoByPlateNum(carinfo); if (carList == null || (carList != null && carList.size() <= 0)) { List<UserRelationCarInfo> list = userService.getRelationCarInfo(user_id); //?user_id ? int i = 0; for (UserRelationCarInfo terminalCar : list) { if ("1".equals(terminalCar.getIs_default())) { i++; } } UserRelationCarInfo userRelationCarInfo = new UserRelationCarInfo(); ////// 20150421 int car_id = carInfoService.queryId("car_id") + 1; //?? TestUpd testupd = new TestUpd(); testupd.setName("car_id"); testupd.setValue(car_id); carInfoService.updtestupd(testupd); //?? /////end carinfo.setCar_id(car_id); carInfoService.carhotInsert(carinfo); userRelationCarInfo.setCar_id(car_id); userRelationCarInfo.setUser_id(user_id.intValue()); if (i > 0) { userRelationCarInfo.setIs_default("0"); userService.insertRelationUserAndCar(userRelationCarInfo); //terminal_car?? } else { userRelationCarInfo.setIs_default("1"); userService.insertRelationUserAndCar(userRelationCarInfo); } responseBodyJson.writeNumberField("result", 1); //?? } else { throw new ShopBusiException(ShopBusiErrorBundle.COMMON, new Object[] { "?" }); } } else { throw new ShopBusiException(ShopBusiErrorBundle.COMMON, new Object[] { "?" }); } }
From source file:com.abiquo.server.core.infrastructure.DatacenterDAO.java
/** * TODO: create queries/*from ww w .j a v a 2 s. c om*/ * * @param datacenterId * @param enterpriseId * @return */ public DefaultEntityCurrentUsed getCurrentResourcesAllocated(final int datacenterId, final int enterpriseId) { Object[] vmResources = (Object[]) getSession().createSQLQuery(SUM_VM_RESOURCES) .setParameter("datacenterId", datacenterId).setParameter("enterpriseId", enterpriseId) .uniqueResult(); Long cpu = vmResources[0] == null ? 0 : ((BigDecimal) vmResources[0]).longValue(); Long ram = vmResources[1] == null ? 0 : ((BigDecimal) vmResources[1]).longValue(); Long hd = vmResources[2] == null ? 0 : ((BigDecimal) vmResources[2]).longValue(); BigDecimal extraHd = (BigDecimal) getSession().createSQLQuery(SUM_EXTRA_HD_RESOURCES) .setParameter("datacenterId", datacenterId).uniqueResult(); Long hdTot = extraHd == null ? hd : hd + extraHd.longValue() * 1024 * 1024; BigDecimal storage = (BigDecimal) getSession().createSQLQuery(SUM_STORAGE_RESOURCES) .setParameter("datacenterId", datacenterId).setParameter("enterpriseId", enterpriseId) .uniqueResult(); BigInteger publicIps = (BigInteger) getSession().createSQLQuery(COUNT_IP_RESOURCES) .setParameter("datacenterId", datacenterId).setParameter("enterpriseId", enterpriseId) .uniqueResult(); BigInteger vlan = (BigInteger) getSession().createSQLQuery(COUNT_VLAN_RESOURCES) .setParameter("datacenterId", datacenterId).setParameter("enterpriseId", enterpriseId) .uniqueResult(); DefaultEntityCurrentUsed used = new DefaultEntityCurrentUsed(cpu.intValue(), ram, hdTot); // Storage usage is stored in MB used.setStorage(storage == null ? 0 : storage.longValue() * 1024 * 1024); used.setPublicIp(publicIps == null ? 0 : publicIps.longValue()); used.setVlanCount(vlan == null ? 0 : vlan.longValue()); return used; }
From source file:org.saiku.web.rest.resources.QueryResource.java
@GET @Produces({ "application/json" }) @Path("/{queryname}/explain") public QueryResult getExplainPlan(@PathParam("queryname") String queryName) { if (log.isDebugEnabled()) { log.debug("TRACK\t" + "\t/query/" + queryName + "/explain\tGET"); }/*from w ww .j a va2 s .c om*/ QueryResult rsc; ResultSet rs = null; try { Long start = (new Date()).getTime(); rs = olapQueryService.explain(queryName); rsc = RestUtil.convert(rs); Long runtime = (new Date()).getTime() - start; rsc.setRuntime(runtime.intValue()); } catch (Exception e) { log.error("Cannot get explain plan for query (" + queryName + ")", e); String error = ExceptionUtils.getRootCauseMessage(e); rsc = new QueryResult(error); } // no need to close resultset, its an EmptyResultset return rsc; }