List of usage examples for java.lang NumberFormatException printStackTrace
public void printStackTrace()
From source file:com.lhfs.fsn.dao.testReport.impl.TestReportDaoImpl.java
/** * ???// w w w . ja v a2s .c o m */ @Override public Integer countByIdAndTypeOrg(long product_id, String type, String pDate, Long organization) { Integer count = 0; try { String condition = " "; if (pDate != null && (!"".equals(pDate))) { condition = " AND ip.production_date between ?4 and ?5 "; } String sql = " SELECT count(*) FROM test_result tr " + "LEFT JOIN product_instance ip ON ip.id=tr.sample_id " + "LEFT JOIN product p ON p.id=ip.product_id WHERE DATEDIFF(ip.expiration_date , SYSDATE()) > 0 AND p.id=?1 AND " + "tr.test_type=?2 AND tr.organization=?3 AND tr.publish_flag='1' " + condition; Query query = entityManager.createNativeQuery(sql); query.setParameter(1, product_id); query.setParameter(2, type); query.setParameter(3, organization); if (pDate != null && (!"".equals(pDate))) { query.setParameter(4, pDate + " 00:00:00"); query.setParameter(5, pDate + " 23:59:59"); } Object result = query.getSingleResult(); count = result != null ? Integer.parseInt(result.toString()) : 0; } catch (NumberFormatException e) { e.printStackTrace(); } return count; }
From source file:com.gettec.fsnip.fsn.dao.business.impl.BusinessUnitDAOImpl.java
@SuppressWarnings("unchecked") @Override// ww w . ja v a 2s . co m public List<BussinessUnitVOToPortal> getBuVOToPortalByBarcode(String barcode) { List<BussinessUnitVOToPortal> bus = new ArrayList<BussinessUnitVOToPortal>(); try { String sql = "SELECT DISTINCT t.id,t.name,t.address,t.jg_lic_url,t.jg_dis_url,t.jg_qs_url,t.qs_no "; sql += " FROM ("; sql += "SELECT bu.id,bu.name,bu.address,bu.jg_lic_url,bu.jg_dis_url,bu.jg_qs_url, "; sql += "(SELECT MAX(pis.qs_no) FROM product_instance pis WHERE pis.product_id=p.id) qs_no "; sql += "FROM business_unit bu "; sql += "INNER JOIN product p ON bu.id = p.producer_id "; sql += "WHERE p.barcode = ?1 "; sql += "UNION ALL "; sql += "SELECT bus.id,bus.name,bus.address,bus.jg_lic_url,bus.jg_dis_url,bus.jg_qs_url, "; sql += "(SELECT MAX(pis.qs_no) FROM product_instance pis WHERE pis.product_id=ps.id) qs_no "; sql += "FROM business_unit bus "; sql += "INNER JOIN product_business_license pbl ON bus.id = pbl.business_id "; sql += "INNER JOIN product ps ON pbl.product_id = ps.id "; sql += "WHERE ps.barcode = ?1 ) t "; Query query = entityManager.createNativeQuery(sql); query.setParameter(1, barcode); List<Object[]> objs = query.getResultList(); if (objs != null && objs.size() > 0) { for (Object[] obj : objs) { BussinessUnitVOToPortal bu = new BussinessUnitVOToPortal(); bu.setId(obj[0] != null ? Long.parseLong(obj[0].toString()) : -1L); bu.setName(obj[1] != null ? obj[1].toString() : ""); bu.setAddress(obj[2] != null ? obj[2].toString() : ""); bu.setLicImg(obj[3] != null ? obj[3].toString() : ""); bu.setDisImg(obj[4] != null ? obj[4].toString() : ""); bu.setQsImg(obj[5] != null ? obj[5].toString() : ""); bu.setQs_no(obj[6] != null ? obj[6].toString() : ""); bus.add(bu); } } } catch (NumberFormatException e) { e.printStackTrace(); } return bus; }
From source file:com.gettec.fsnip.fsn.dao.business.impl.BusinessUnitDAOImpl.java
@SuppressWarnings("unchecked") @Override/* w w w .j ava 2 s . c o m*/ public List<Resource> getByIdResourceList(Long id, String strColumn) { List<Resource> resList = new ArrayList<Resource>(); try { String sql = " SELECT pbl.id,pbl.business_name,"; sql += " ttr.RESOURCE_ID,ttr.FILE_NAME,ttr.RESOURCE_NAME,ttr.URL,ttr.UPLOAD_DATE,tsrt.RESOURCE_TYPE_ID,"; sql += " tsrt.CONTENT_TYPE,tsrt.RESOURCE_TYPE_DESC,tsrt.RESOURCE_TYPE_NAME FROM product_business_license pbl "; sql += " LEFT JOIN t_test_resource ttr ON ttr.RESOURCE_ID = " + strColumn; sql += " LEFT JOIN T_SYS_RESOURCE_TYPE tsrt ON tsrt.RESOURCE_TYPE_ID = ttr.RESOURCE_TYPE_ID "; sql += " WHERE product_id = ?1 ORDER BY pbl.id ASC "; Query query = entityManager.createNativeQuery(sql); query.setParameter(1, id); List<Object[]> objs = query.getResultList(); for (Object[] obj : objs) { Resource res = new Resource(); res.setBusinessToId(obj[0] == null ? null : Long.parseLong(obj[0].toString())); res.setBusinessName(obj[1] == null ? null : obj[1].toString()); res.setId(obj[2] == null ? null : Long.parseLong(obj[2].toString())); res.setFileName(obj[3] == null ? null : obj[3].toString()); res.setName(obj[4] == null ? null : obj[4].toString()); res.setUrl(obj[5] == null ? null : obj[5].toString()); res.setUploadDate(obj[6] == null ? null : (Date) obj[6]); ResourceType rt = new ResourceType(); rt.setRtId(obj[7] == null ? null : Long.parseLong(obj[7].toString())); rt.setContentType(obj[8] == null ? null : obj[8].toString()); rt.setRtDesc(obj[9] == null ? null : obj[9].toString()); rt.setRtName(obj[10] == null ? null : obj[10].toString()); res.setType(rt); resList.add(res); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resList; }
From source file:org.generationcp.breeding.manager.crosses.NurseryTemplateConditionsComponent.java
private TextField getTextFieldBreederId() { breederId.addListener(new Property.ValueChangeListener() { private static final long serialVersionUID = 1L; @Override// w w w . j av a 2 s .co m public void valueChange(ValueChangeEvent event) { Person p = new Person(); User u = new User(); String name = ""; boolean noError = true; try { u = userDataManager.getUserById(Integer.valueOf(breederId.getValue().toString())); } catch (NumberFormatException e) { noError = false; } catch (MiddlewareQueryException e) { noError = false; } if (u != null && noError) { try { p = userDataManager.getPersonById(u.getPersonid()); if (p != null) { name = p.getFirstName() + " " + p.getMiddleName() + " " + p.getLastName(); } else { comboBoxBreedersName.setValue(comboBoxBreedersName.getNullSelectionItemId()); breederId.setValue(""); } } catch (MiddlewareQueryException e) { // TODO Auto-generated catch block e.printStackTrace(); } comboBoxBreedersName.setValue(name); } else { if (comboBoxBreedersName.getValue() != null || u == null) { MessageNotifier.showWarning("Warning!", messageSource.getMessage(Message.INVALID_BREEDER_ID), Position.MIDDLE_CENTER); } comboBoxBreedersName.setValue(comboBoxBreedersName.getNullSelectionItemId()); breederId.setValue(""); } } }); return breederId; }
From source file:com.gettec.fsnip.fsn.dao.member.impl.MemberDAOImpl.java
@Override public Long getMemberStaCountByConfigureData(Long businessId, String memberName, String barcode) { String sql = " SELECT count(*) "; sql += " FROM member p "; sql += " LEFT JOIN business_unit bu ON p.organization = bu.organization "; sql += " WHERE bu.id=:buId "; if (memberName != null && !"".equals(memberName)) { sql += " AND p.name LIKE '%" + memberName + "%' "; }//from ww w .j a v a 2 s. c om if (barcode != null && !"".equals(barcode)) { sql += " AND p.barcode LIKE '%" + barcode + "%'"; } Long counts = 0l; try { Query query = entityManager.createNativeQuery(sql); query.setParameter("buId", businessId); Object rtn = query.getSingleResult(); counts = rtn == null ? 0 : Long.parseLong(rtn.toString()); } catch (NumberFormatException e) { e.printStackTrace(); } return counts; }
From source file:de.ipbhalle.metfrag.pubchem.PubChemWebService.java
/** * //w w w . jav a 2s . c o m * @author c-ruttkies * * * @param filename * @throws AxisFault */ private boolean savingRetrievedHits(File filename, Vector<String> cidsVec) throws AxisFault { org.apache.commons.httpclient.params.DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy", org.apache.commons.httpclient.cookie.CookiePolicy.BROWSER_COMPATIBILITY); PUGStub ps = new PUGStub(); ps._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false); ps._getServiceClient().getOptions().setTimeOutInMilliSeconds(5 * 60 * 1000); ArrayOfInt aoi = new ArrayOfInt(); InputList il = new InputList(); il.setIdType(gov.nih.nlm.ncbi.pubchemAxis2.PCIDType.eID_CID); Download d = new Download(); d.setEFormat(gov.nih.nlm.ncbi.pubchemAxis2.FormatType.eFormat_SDF); d.setECompress(gov.nih.nlm.ncbi.pubchemAxis2.CompressType.eCompress_None); d.setUse3D(false); int[] cids = new int[cidsVec.size()]; for (int i = 0; i < cidsVec.size(); i++) { try { cids[i] = Integer.parseInt(cidsVec.get(i)); } catch (java.lang.NumberFormatException e) { System.err.println("Error: " + cidsVec.get(i) + " is no valid pubchem ID!"); return false; } } aoi.set_int(cids); il.setIds(aoi); InputListResponse ilr = null; try { ilr = ps.inputList(il); } catch (RemoteException e) { System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } if (ilr == null) { System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!"); return false; } String listKey = ilr.getListKey(); d.setListKey(listKey); DownloadResponse dr = null; try { dr = ps.download(d); } catch (RemoteException e) { System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } gov.nih.nlm.ncbi.pubchemAxis2.GetOperationStatus req4 = new GetOperationStatus(); AnyKeyType anyKey = new AnyKeyType(); anyKey.setAnyKey(dr.getDownloadKey()); req4.setGetOperationStatus(anyKey); gov.nih.nlm.ncbi.pubchemAxis2.StatusType status; try { if (this.verbose) System.out.print("downloading compounds from pubchem"); while ((status = ps.getOperationStatus(req4) .getStatus()) == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Running || status == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Queued) { Thread.sleep(2000); if (this.verbose) System.out.print("."); } } catch (RemoteException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } catch (InterruptedException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } if (status == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Success) { GetDownloadUrl req5 = new GetDownloadUrl(); req5.setDownloadKey(dr.getDownloadKey()); URL url = null; try { url = new URL(ps.getDownloadUrl(req5).getUrl()); } catch (MalformedURLException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } catch (RemoteException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } if (this.verbose) System.out.println("\ndownload finished!"); URLConnection fetch; InputStream input; try { fetch = url.openConnection(); input = fetch.getInputStream(); } catch (IOException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } FileOutputStream output; try { output = new FileOutputStream(filename.getAbsoluteFile()); } catch (FileNotFoundException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } byte[] buffer = new byte[10000]; int n; try { while ((n = input.read(buffer)) > 0) output.write(buffer, 0, n); output.close(); } catch (IOException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } } else { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); return false; } FileInputStream in = null; try { in = new FileInputStream(filename); } catch (FileNotFoundException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); return false; } MDLV2000Reader reader = new MDLV2000Reader(in); ChemFile fileContents; try { fileContents = (ChemFile) reader.read(new ChemFile()); } catch (CDKException e) { System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!"); e.printStackTrace(); return false; } SmilesGenerator generatorSmiles = new SmilesGenerator(); for (int i = 0; i < fileContents.getChemSequence(0).getChemModelCount(); i++) { this.containers .add(fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet().getAtomContainer(0)); Map<Object, Object> properties = fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet() .getAtomContainer(0).getProperties(); this.retrievedHits.put(Integer.parseInt(properties.get("PUBCHEM_COMPOUND_CID").toString()), generatorSmiles.createSMILES( fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet().getMolecule(0))); } return true; }
From source file:com.tiempometa.muestradatos.JReadTags.java
@Override public void handleReadings(List<TagReading> readings) { bibLabel.setText(""); if (readings.size() > 0) { if (readings.size() == 1) { statusLabel.setBackground(Color.cyan); statusLabel.setText("Leyendo tag"); for (TagReading tagReading : readings) { logger.info("Tag data dump"); logger.info(tagReading.getTagReadData().getTag().epcString()); logger.info(String.valueOf(tagReading.getTagReadData().getData().length)); logger.info(Hex.encodeHexString(tagReading.getTagReadData().getData())); logger.info(String.valueOf(tagReading.getTagReadData().getEPCMemData().length)); logger.info(Hex.encodeHexString(tagReading.getTagReadData().getEPCMemData())); logger.info(String.valueOf(tagReading.getTagReadData().getTIDMemData().length)); logger.info(Hex.encodeHexString(tagReading.getTagReadData().getTIDMemData())); logger.info(String.valueOf(tagReading.getTagReadData().getReservedMemData().length)); logger.info(Hex.encodeHexString(tagReading.getTagReadData().getReservedMemData())); logger.info(String.valueOf(tagReading.getTagReadData().getUserMemData().length)); logger.info(Hex.encodeHexString(tagReading.getTagReadData().getUserMemData())); if (tagReading.getTid() == null) { try { tagReading.setTid(ReaderContext.readTid(tagReading.getEpc(), 12)); if (logger.isDebugEnabled()) { logger.debug("Got tag " + tagReading.getEpc() + " - " + tagReading.getTid()); }//w w w . j a v a 2s. c o m try { statusLabel.setBackground(Color.green); statusLabel.setText("Tag leido"); tidTextField.setText(tagReading.getTid()); epcTextField.setText(tagReading.getEpc()); String rfidString = null; switch (dataToStoreComboBox.getSelectedIndex()) { case 0: rfidString = tagReading.getEpc(); break; case 1: rfidString = tagReading.getTid(); break; default: break; } List<Rfid> rfids = rfidDao.findByRfid(rfidString); if (rfids.size() == 0) { String bib = nextBibTextField.getText(); Rfid bibRfid = rfidDao.fetchByBib(bib); if ((bibRfid != null) & (!allowDuplicateBibsCheckBox.isSelected())) { JOptionPane.showMessageDialog(this, "Ese nmero ya ha sido capturado", "Nmero duplicado", JOptionPane.ERROR_MESSAGE); } else { Integer chipNumber = null; try { chipNumber = Integer.valueOf(bib); Rfid rfid = new Rfid(null, null, bib, rfidString, chipNumber, Rfid.STATUS_NOT_ASSIGNED); rfidDao.save(rfid); tagTableModel.getData().add(rfid); tagTableModel.fireTableDataChanged(); statusLabel.setText("Tag guardado"); chipNumber = chipNumber + 1; nextBibTextField.setText(String.valueOf(chipNumber)); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "El valor de nmero debe ser numrico", "Error de datos", JOptionPane.ERROR_MESSAGE); } } } else { statusLabel.setBackground(Color.red); statusLabel.setText("Tag ya leido"); Rfid rfid = rfids.get(0); bibLabel.setText(rfid.getBib()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (SQLException e1) { JOptionPane.showMessageDialog(this, "Error guardando tag: " + e1.getMessage(), "Error de base de datos", JOptionPane.ERROR_MESSAGE); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } statusLabel.setBackground(Color.white); statusLabel.setText("Remover tag"); } catch (ReaderException e) { // TODO Auto-generated catch block e.printStackTrace(); statusLabel.setBackground(Color.red); } } } } else { statusLabel.setBackground(Color.orange); statusLabel.setText("Dos o ms tags"); } } else { statusLabel.setBackground(Color.yellow); statusLabel.setText("Sin tag"); } }
From source file:org.dasein.cloud.nimbula.network.Vethernet.java
@Override public @Nonnull VLAN createVlan(@Nonnull String cidr, @Nonnull String name, @Nonnull String description, @Nonnull String domainName, @Nonnull String[] dnsServers, @Nonnull String[] ntpServers) throws CloudException, InternalException { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); }/*from ww w . j a va 2 s.c o m*/ if (!"root".equals(ctx.getAccountNumber())) { throw new OperationNotSupportedException("VLAN creation is not yet supported for non-root"); } int id = findId(); int[] parts = new int[4]; int idx = cidr.indexOf('/'); int mask = 32; if (idx > -1) { mask = Integer.parseInt(cidr.substring(idx + 1)); cidr = cidr.substring(0, idx); } String[] dotted = cidr.split("\\."); if (dotted.length != 4) { throw new CloudException("Invalid IP address: " + cidr); } int i = 0; for (String dot : dotted) { try { parts[i++] = Integer.parseInt(dot); } catch (NumberFormatException e) { throw new CloudException("Invalid IP address: " + cidr); } } HashMap<String, Object> state = new HashMap<String, Object>(); state.put("id", id); state.put("description", description); state.put("type", "vlan"); state.put("uri", null); try { state.put("name", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id); } catch (UnsupportedEncodingException e) { if (logger.isDebugEnabled()) { logger.error("Failed UTF-8 encoding: " + e.getMessage()); e.printStackTrace(); } throw new InternalException(e); } NimbulaMethod method = new NimbulaMethod(cloud, "vethernet"); method.post(state); VLAN vlan; try { vlan = toVlan(method.getResponseBody()); } catch (JSONException e) { if (logger.isDebugEnabled()) { logger.error("Error parsing JSON: " + e.getMessage()); e.printStackTrace(); } throw new CloudException(e); } state.clear(); String ipStop; if (mask == 32 || mask == 31) { ipStop = cidr; } else { if (mask >= 24) { int count = ((int) Math.pow(2, (32 - mask)) - 1); if (count > 4) { count = count - 4; } parts[3] = parts[3] + count; } else if (mask >= 16) { int count = ((int) Math.pow(2, (24 - mask)) - 1); if (count > 4) { count = count - 4; } parts[2] = parts[2] + count; } else if (mask >= 8) { int count = ((int) Math.pow(2, (16 - mask)) - 1); if (count > 4) { count = count - 4; } parts[1] = parts[1] + count; } else { int count = ((int) Math.pow(2, (8 - mask)) - 1); if (count > 4) { count = count - 4; } parts[0] = parts[0] + count; } ipStop = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]; } state.put("iprange_mask", mask); state.put("dns_server", dnsServers[0]); state.put("dns_server_standby", dnsServers[1]); state.put("iprange_start", cidr); state.put("iprange_stop", ipStop); state.put("uri", null); try { state.put("vethernet", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id); state.put("name", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vdhcpd" + id); } catch (UnsupportedEncodingException e) { if (logger.isDebugEnabled()) { logger.error("Encoding error: " + e.getMessage()); e.printStackTrace(); } throw new InternalException(e); } int slash = cidr.indexOf('/'); state.put("iprouter", cidr.subSequence(0, slash)); method = new NimbulaMethod(cloud, VDHCPD); method.post(state); return vlan; }
From source file:org.fao.geonet.Geonetwork.java
/** * Inits the engine, loading all needed data. *///from w w w. j a v a2s . c om @SuppressWarnings(value = "unchecked") public Object start(Element config, ServiceContext context) throws Exception { logger = context.getLogger(); path = context.getAppPath(); String baseURL = context.getBaseUrl(); String webappName = baseURL.substring(1); // TODO : if webappName is "". ie no context ServletContext servletContext = null; if (context.getServlet() != null) { servletContext = context.getServlet().getServletContext(); } ServerLib sl = new ServerLib(servletContext, path); String version = sl.getVersion(); String subVersion = sl.getSubVersion(); logger.info("Initializing GeoNetwork " + version + "." + subVersion + " ..."); // Get main service config handler ServiceConfig handlerConfig = new ServiceConfig(config.getChildren()); // Init configuration directory new GeonetworkDataDirectory(webappName, path, handlerConfig, context.getServlet()); // Get config handler properties String systemDataDir = handlerConfig.getMandatoryValue(Geonet.Config.SYSTEM_DATA_DIR); String thesauriDir = handlerConfig.getMandatoryValue(Geonet.Config.CODELIST_DIR); String luceneDir = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_DIR); String dataDir = handlerConfig.getMandatoryValue(Geonet.Config.DATA_DIR); String luceneConfigXmlFile = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_CONFIG); String summaryConfigXmlFile = handlerConfig.getMandatoryValue(Geonet.Config.SUMMARY_CONFIG); logger.info("Data directory: " + systemDataDir); setProps(path, handlerConfig); Class statusActionsClass = setupStatusActions(handlerConfig); String languageProfilesDir = handlerConfig.getMandatoryValue(Geonet.Config.LANGUAGE_PROFILES_DIR); JeevesJCS.setConfigFilename(path + "WEB-INF/classes/cache.ccf"); // force caches to be config'd so shutdown hook works correctly JeevesJCS.getInstance(Processor.XLINK_JCS); JeevesJCS.getInstance(XmlResolver.XMLRESOLVER_JCS); // --- Check current database and create database if an emty one is found String dbConfigurationFilePath = path + "/WEB-INF/config-db.xml"; dbConfiguration = Xml.loadFile(dbConfigurationFilePath); ConfigurationOverrides.DEFAULT.updateWithOverrides(dbConfigurationFilePath, servletContext, path, dbConfiguration); Pair<Dbms, Boolean> pair = initDatabase(context); Dbms dbms = pair.one(); Boolean created = pair.two(); //------------------------------------------------------------------------ //--- initialize thread pool logger.info(" - Thread Pool..."); threadPool = new ThreadPool(); //------------------------------------------------------------------------ //--- initialize settings subsystem logger.info(" - Setting manager..."); SettingManager settingMan = new SettingManager(dbms, context.getProviderManager()); // --- Migrate database if an old one is found migrateDatabase(servletContext, dbms, settingMan, version, subVersion, context.getAppPath()); //--- initialize ThreadUtils with setting manager and rm props ThreadUtils.init(context.getResourceManager().getProps(Geonet.Res.MAIN_DB), settingMan); //------------------------------------------------------------------------ //--- initialize Z39.50 logger.info(" - Z39.50..."); boolean z3950Enable = settingMan.getValueAsBool("system/z3950/enable", false); String z3950port = settingMan.getValue("system/z3950/port"); // null means not initialized ApplicationContext app_context = null; // build Z3950 repositories file first from template URL url = getClass().getClassLoader().getResource(Geonet.File.JZKITCONFIG_TEMPLATE); if (Repositories.build(url, context)) { logger.info(" Repositories file built from template."); try { app_context = new ClassPathXmlApplicationContext(Geonet.File.JZKITAPPLICATIONCONTEXT); // to have access to the GN context in spring-managed objects ContextContainer cc = (ContextContainer) app_context.getBean("ContextGateway"); cc.setSrvctx(context); if (!z3950Enable) logger.info(" Server is Disabled."); else { logger.info(" Server is Enabled."); Server.init(z3950port, app_context); } } catch (Exception e) { logger.error( " Repositories file init FAILED - Z3950 server disabled and Z3950 client services (remote search, harvesting) may not work. Error is:" + e.getMessage()); e.printStackTrace(); } } else { logger.error( " Repositories file builder FAILED - Z3950 server disabled and Z3950 client services (remote search, harvesting) may not work."); } //------------------------------------------------------------------------ //--- initialize SchemaManager logger.info(" - Schema manager..."); String schemaPluginsDir = handlerConfig.getMandatoryValue(Geonet.Config.SCHEMAPLUGINS_DIR); String schemaCatalogueFile = systemDataDir + "config" + File.separator + Geonet.File.SCHEMA_PLUGINS_CATALOG; boolean createOrUpdateSchemaCatalog = handlerConfig .getMandatoryValue(Geonet.Config.SCHEMA_PLUGINS_CATALOG_UPDATE).equals("true"); logger.info(" - Schema plugins directory: " + schemaPluginsDir); logger.info(" - Schema Catalog File : " + schemaCatalogueFile); SchemaManager schemaMan = SchemaManager.getInstance(path, Resources.locateResourcesDir(context), schemaCatalogueFile, schemaPluginsDir, context.getLanguage(), handlerConfig.getMandatoryValue(Geonet.Config.PREFERRED_SCHEMA), createOrUpdateSchemaCatalog); //------------------------------------------------------------------------ //--- initialize search and editing logger.info(" - Search..."); boolean logSpatialObject = "true" .equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_SPATIAL_OBJECTS)); boolean logAsynch = "true".equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_ASYNCH)); logger.info(" - Log spatial object: " + logSpatialObject); logger.info(" - Log in asynch mode: " + logAsynch); String luceneTermsToExclude = ""; luceneTermsToExclude = handlerConfig.getMandatoryValue(Geonet.Config.STAT_LUCENE_TERMS_EXCLUDE); LuceneConfig lc = new LuceneConfig(path, servletContext, luceneConfigXmlFile); logger.info(" - Lucene configuration is:"); logger.info(lc.toString()); DataStore dataStore = context.getResourceManager().getDataStore(Geonet.Res.MAIN_DB); if (dataStore == null) { dataStore = createShapefileDatastore(luceneDir); } //--- no datastore for spatial indexing means that we can't continue if (dataStore == null) { throw new IllegalArgumentException( "GeoTools datastore creation failed - check logs for more info/exceptions"); } String maxWritesInTransactionStr = handlerConfig.getMandatoryValue(Geonet.Config.MAX_WRITES_IN_TRANSACTION); int maxWritesInTransaction = SpatialIndexWriter.MAX_WRITES_IN_TRANSACTION; try { maxWritesInTransaction = Integer.parseInt(maxWritesInTransactionStr); } catch (NumberFormatException nfe) { logger.error( "Invalid config parameter: maximum number of writes to spatial index in a transaction (maxWritesInTransaction), Using " + maxWritesInTransaction + " instead."); nfe.printStackTrace(); } String htmlCacheDir = handlerConfig.getMandatoryValue(Geonet.Config.HTMLCACHE_DIR); SettingInfo settingInfo = new SettingInfo(settingMan); searchMan = new SearchManager(path, luceneDir, htmlCacheDir, thesauriDir, summaryConfigXmlFile, lc, logAsynch, logSpatialObject, luceneTermsToExclude, dataStore, maxWritesInTransaction, settingInfo, schemaMan, servletContext); // if the validator exists the proxyCallbackURL needs to have the external host and // servlet name added so that the cas knows where to send the validation notice ServerBeanPropertyUpdater.updateURL(settingInfo.getSiteUrl(true) + baseURL, servletContext); //------------------------------------------------------------------------ //--- extract intranet ip/mask and initialize AccessManager logger.info(" - Access manager..."); AccessManager accessMan = new AccessManager(dbms, settingMan); //------------------------------------------------------------------------ //--- get edit params and initialize DataManager logger.info(" - Xml serializer and Data manager..."); String useSubversion = handlerConfig.getMandatoryValue(Geonet.Config.USE_SUBVERSION); SvnManager svnManager = null; XmlSerializer xmlSerializer = null; if (useSubversion.equals("true")) { String subversionPath = handlerConfig.getValue(Geonet.Config.SUBVERSION_PATH); svnManager = new SvnManager(context, settingMan, subversionPath, dbms, created); xmlSerializer = new XmlSerializerSvn(settingMan, svnManager); } else { xmlSerializer = new XmlSerializerDb(settingMan); } DataManagerParameter dataManagerParameter = new DataManagerParameter(); dataManagerParameter.context = context; dataManagerParameter.svnManager = svnManager; dataManagerParameter.searchManager = searchMan; dataManagerParameter.xmlSerializer = xmlSerializer; dataManagerParameter.schemaManager = schemaMan; dataManagerParameter.accessManager = accessMan; dataManagerParameter.dbms = dbms; dataManagerParameter.settingsManager = settingMan; dataManagerParameter.baseURL = baseURL; dataManagerParameter.dataDir = dataDir; dataManagerParameter.thesaurusDir = thesauriDir; dataManagerParameter.appPath = path; DataManager dataMan = new DataManager(dataManagerParameter); /** * Initialize iso languages mapper */ IsoLanguagesMapper.getInstance().init(dbms); /** * Initialize language detector */ LanguageDetector.init(path + languageProfilesDir, context, dataMan); //------------------------------------------------------------------------ //--- Initialize thesaurus logger.info(" - Thesaurus..."); thesaurusMan = ThesaurusManager.getInstance(context, path, dataMan, context.getResourceManager(), thesauriDir); //------------------------------------------------------------------------ //--- initialize catalogue services for the web logger.info(" - Catalogue services for the web..."); CatalogConfiguration.loadCatalogConfig(path, Csw.CONFIG_FILE); CatalogDispatcher catalogDis = new CatalogDispatcher(new File(path, summaryConfigXmlFile), lc); //------------------------------------------------------------------------ //--- initialize catalogue services for the web logger.info(" - Open Archive Initiative (OAI-PMH) server..."); OaiPmhDispatcher oaipmhDis = new OaiPmhDispatcher(settingMan, schemaMan); //------------------------------------------------------------------------ //--- initialize metadata notifier subsystem MetadataNotifierManager metadataNotifierMan = new MetadataNotifierManager(dataMan); logger.info(" - Metadata notifier ..."); //------------------------------------------------------------------------ //--- initialize metadata notifier subsystem logger.info(" - Metadata notifier ..."); //------------------------------------------------------------------------ //--- return application context GeonetContext gnContext = new GeonetContext(); gnContext.accessMan = accessMan; gnContext.dataMan = dataMan; gnContext.searchMan = searchMan; gnContext.schemaMan = schemaMan; gnContext.config = handlerConfig; gnContext.catalogDis = catalogDis; gnContext.settingMan = settingMan; gnContext.thesaurusMan = thesaurusMan; gnContext.oaipmhDis = oaipmhDis; gnContext.app_context = app_context; gnContext.metadataNotifierMan = metadataNotifierMan; gnContext.threadPool = threadPool; gnContext.xmlSerializer = xmlSerializer; gnContext.svnManager = svnManager; gnContext.statusActionsClass = statusActionsClass; logger.info("Site ID is : " + gnContext.getSiteId()); //------------------------------------------------------------------------ //--- initialize harvesting subsystem logger.info(" - Harvest manager..."); harvestMan = new HarvestManager(context, gnContext, settingMan, dataMan); dataMan.setHarvestManager(harvestMan); gnContext.harvestMan = harvestMan; // Creates a default site logo, only if the logo image doesn't exists // This can happen if the application has been updated with a new version preserving the database and // images/logos folder is not copied from old application createSiteLogo(gnContext.getSiteId(), servletContext, context.getAppPath()); // Notify unregistered metadata at startup. Needed, for example, when the user enables the notifier config // to notify the existing metadata in database // TODO: Fix DataManager.getUnregisteredMetadata and uncomment next lines metadataNotifierControl = new MetadataNotifierControl(context, gnContext); metadataNotifierControl.runOnce(); //--- load proxy information from settings into Jeeves for observers such //--- as jeeves.utils.XmlResolver to use ProxyInfo pi = JeevesProxyInfo.getInstance(); boolean useProxy = settingMan.getValueAsBool("system/proxy/use", false); if (useProxy) { String proxyHost = settingMan.getValue("system/proxy/host"); String proxyPort = settingMan.getValue("system/proxy/port"); String username = settingMan.getValue("system/proxy/username"); String password = settingMan.getValue("system/proxy/password"); pi.setProxyInfo(proxyHost, Integer.valueOf(proxyPort), username, password); } // // db heartbeat configuration -- for failover to readonly database // boolean dbHeartBeatEnabled = Boolean .parseBoolean(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_ENABLED, "false")); if (dbHeartBeatEnabled) { Integer dbHeartBeatInitialDelay = Integer .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_INITIALDELAYSECONDS, "5")); Integer dbHeartBeatFixedDelay = Integer .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_FIXEDDELAYSECONDS, "60")); createDBHeartBeat(context.getResourceManager(), gnContext, dbHeartBeatInitialDelay, dbHeartBeatFixedDelay); } return gnContext; }
From source file:org.matsim.pt2matsim.gtfs.GtfsFeedImpl.java
protected void loadTransfers() { log.info("Looking for transfers.txt"); boolean transfersFileFound = true; // transfers are optional try {//from w ww. j a v a 2s .co m CSVReader reader = createCSVReader(root + GtfsDefinitions.Files.TRANSFERS.fileName); String[] header = reader.readNext(); Map<String, Integer> col = getIndices(header, GtfsDefinitions.Files.TRANSFERS.columns, GtfsDefinitions.Files.TRANSFERS.optionalColumns); String[] line = reader.readNext(); while (line != null) { String fromStopId = line[col.get(GtfsDefinitions.FROM_STOP_ID)]; String toStopId = line[col.get(GtfsDefinitions.TO_STOP_ID)]; GtfsDefinitions.TransferType transferType = GtfsDefinitions.TransferType.values()[Integer .parseInt(line[col.get(GtfsDefinitions.TRANSFER_TYPE)])]; if (transferType.equals(GtfsDefinitions.TransferType.REQUIRES_MIN_TRANSFER_TIME)) { try { int minTransferTime = Integer.parseInt(line[col.get(GtfsDefinitions.MIN_TRANSFER_TIME)]); transfers.add(new TransferImpl(fromStopId, toStopId, transferType, minTransferTime)); } catch (NumberFormatException e) { throw new IllegalArgumentException("No required minimal transfer time set for transfer " + line[col.get(GtfsDefinitions.FROM_STOP_ID)] + " -> " + line[col.get(GtfsDefinitions.TO_STOP_ID)] + "!"); } } else { // store transfer transfers.add(new TransferImpl(fromStopId, toStopId, transferType)); } line = reader.readNext(); } reader.close(); } catch (ArrayIndexOutOfBoundsException i) { throw new RuntimeException("Emtpy line found in transfers.txt"); } catch (FileNotFoundException e) { log.info("... no transfers file found"); transfersFileFound = false; } catch (IOException e) { e.printStackTrace(); } if (transfersFileFound) { log.info("... transfers.txt loaded"); } }