List of usage examples for java.lang NullPointerException printStackTrace
public void printStackTrace()
From source file:ilearn.orb.controller.AnnotationController.java
@RequestMapping(value = "/annotated/{userid}", method = RequestMethod.POST) public ModelAndView annotatedText(Locale locale, ModelMap modelMap, HttpServletRequest request, HttpSession session, @PathVariable("userid") Integer userid) { try {/* w w w . ja v a 2s .c o m*/ request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } ActiveRule activeRules[] = null; String activatedRules = request.getParameter("activeRules"); if (!activatedRules.trim().isEmpty()) { String p[] = activatedRules.trim().split(","); activeRules = new ActiveRule[p.length]; for (int i = 0; i < p.length; i++) { activeRules[i] = new ActiveRule(); String q[] = p[i].trim().split("_"); activeRules[i].category = Integer.parseInt(q[0]); activeRules[i].index = Integer.parseInt(q[1]); activeRules[i].rule = Integer.parseInt(q[2]); activeRules[i].color = Integer.parseInt(q[3].substring(1), 16); } } ModelAndView model = new ModelAndView(); model.setViewName("annotated"); try { Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer()) .setDateFormat(DateFormat.LONG).create(); User[] students = null; try { String json = UserServices.getProfiles(Integer.parseInt(session.getAttribute("id").toString()), session.getAttribute("auth").toString()); students = gson.fromJson(json, User[].class); } catch (NullPointerException e) { } if (students == null || students.length == 0) { students = HardcodedUsers.defaultStudents(); } modelMap.put("students", students); String text = request.getParameter("inputText"); if (text != null) { text = new String(text.getBytes("8859_1"), "UTF-8"); } else text = ""; modelMap.put("profileId", userid); modelMap.put("text", text); UserProfile pr = retrieveProfile(session, userid); String annotatedJson; if (userid > 0) annotatedJson = TextServices.getAnnotatedText(userid, pr.getLanguage() == LanguageCode.EN ? "EN" : "GR", session.getAttribute("auth").toString(), text); else annotatedJson = TextServices.getAnnotatedText(HardcodedUsers.defaultProfileLanguage(userid), text); annotatedPack = (new Gson()).fromJson(annotatedJson, AnnotatedPack.class); txModule = new TextAnnotationModule(); txModule.setProfile(pr); txModule.initializePresentationModule(); txModule.setInputHTMLFile(annotatedPack.getHtml()); txModule.setJSonObject(annotatedPack.getWordSet()); if (activeRules != null && activeRules.length > 0) { for (ActiveRule ar : activeRules) { txModule.getPresentationRulesModule().setPresentationRule(ar.category, ar.index, ar.rule); txModule.getPresentationRulesModule().setTextColor(ar.category, ar.index, ar.color); txModule.getPresentationRulesModule().setHighlightingColor(ar.category, ar.index, ar.color); txModule.getPresentationRulesModule().setActivated(ar.category, ar.index, true); } } txModule.annotateText(); String result = new String(txModule.getAnnotatedHTMLFile()); modelMap.put("annotatedText", result); } catch (NumberFormatException e) { //e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return model; }
From source file:com.github.michalbednarski.intentslab.editor.IntentEditorActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_run_intent: runIntent();//from w w w. j a v a2s.com return true; case R.id.set_editor_result: updateIntent(); setResult(0, new Intent().putExtra(Editor.EXTRA_VALUE, mEditedIntent)); finish(); return true; case R.id.attach_intent_filter: { // We have specified component, just find IntentFilters for it final ComponentName componentName = mEditedIntent.getComponent(); ExtendedPackageInfo.getExtendedPackageInfo(this, componentName.getPackageName(), new ExtendedPackageInfo.Callback() { @Override public void onPackageInfoAvailable(ExtendedPackageInfo extendedPackageInfo) { try { setAttachedIntentFilters(extendedPackageInfo .getComponentInfo(componentName.getClassName()).intentFilters); Toast.makeText(IntentEditorActivity.this, R.string.intent_filter_attached, Toast.LENGTH_SHORT).show(); } catch (NullPointerException e) { Toast.makeText(IntentEditorActivity.this, R.string.no_intent_filters_found, Toast.LENGTH_SHORT).show(); } } }); } return true; case R.id.detach_intent_filter: clearAttachedIntentFilters(); return true; case R.id.component_info: { ComponentName component = mEditedIntent.getComponent(); startActivity(new Intent(this, SingleFragmentActivity.class) .putExtra(SingleFragmentActivity.EXTRA_FRAGMENT, ComponentInfoFragment.class.getName()) .putExtra(ComponentInfoFragment.ARG_PACKAGE_NAME, component.getPackageName()) .putExtra(ComponentInfoFragment.ARG_COMPONENT_NAME, component.getClassName()) .putExtra(ComponentInfoFragment.ARG_LAUNCHED_FROM_INTENT_EDITOR, true)); } return true; case R.id.save: { updateIntent(); SavedItemsDatabase.getInstance(this).saveIntent(this, mEditedIntent, mComponentType, mMethodId); } return true; case R.id.track_intent: { if (!item.isChecked()) { XIntentsLab xIntentsLab = XIntentsLabStatic.getInstance(); if (xIntentsLab.havePermission()) { createIntentTracker(); } else { try { startIntentSenderForResult( xIntentsLab.getRequestPermissionIntent(getPackageName()).getIntentSender(), REQUEST_CODE_REQUEST_INTENT_TRACKER_PERMISSION, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); // TODO: can we handle this? } } } else { removeIntentTracker(); } return true; } case R.id.disable_interception: getPackageManager().setComponentEnabledSetting( new ComponentName(this, IntentEditorInterceptedActivity.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Toast.makeText(this, R.string.interception_disabled, Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } }
From source file:org.osaf.caldav4j.CalDAVCalendarCollection.java
/** * adds a calendar object to caldav collection using UID.ics as file name * @param httpClient/* w w w . ja va 2 s . c om*/ * @param c * @throws CalDAV4JException */ public void addCalendar(HttpClient httpClient, Calendar c) throws CalDAV4JException { String uid = null; ComponentList cl = c.getComponents(); // get uid from first non VTIMEZONE event Iterator it = cl.iterator(); while ((uid == null) && it.hasNext()) { Object comp = it.next(); if (!(comp instanceof TimeZone)) { CalendarComponent cc = (CalendarComponent) comp; try { uid = cc.getProperty(Property.UID).getValue(); } catch (NullPointerException e) { // TODO log missing uid } } } if (uid == null) { uid = random.nextLong() + "-" + random.nextLong(); } PutMethod putMethod = createPutMethodForNewResource(uid + ".ics", c); try { httpClient.executeMethod(getHostConfiguration(), putMethod); //fixed for nullpointerexception String etag = (putMethod.getResponseHeader("ETag") != null) ? putMethod.getResponseHeader("ETag").getValue() : ""; CalDAVResource calDAVResource = new CalDAVResource(c, etag, getHref((putMethod.getPath()))); cache.putResource(calDAVResource); } catch (Exception e) { throw new CalDAV4JException("Trouble executing PUT", e); } int statusCode = putMethod.getStatusCode(); switch (statusCode) { case CaldavStatus.SC_CREATED: break; case CaldavStatus.SC_NO_CONTENT: break; case CaldavStatus.SC_PRECONDITION_FAILED: break; default: //must be some other problem, throw an exception try { throw new CalDAV4JException( "Unexpected status code: " + statusCode + "\n" + putMethod.getResponseBodyAsString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new CalDAV4JException( "Unexpected status code: " + statusCode + "\n" + "error in getResponseBodyAsString()"); } } }
From source file:fsi_admin.JFsiTareas.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public synchronized void actualizarSaldos() { // Primero recopila la informacion de las bases de datos. Vector BASES = new Vector(); JBDRegistradasSet bdr = new JBDRegistradasSet(null); bdr.ConCat(true);/* ww w . j a va2 s . c o m*/ bdr.Open(); for (int i = 0; i < bdr.getNumRows(); i++) { String nombre = bdr.getAbsRow(i).getNombre(); BASES.addElement(nombre); } short res = 0; String mensaje = ""; Connection con; try { Calendar fecha = GregorianCalendar.getInstance(); FileWriter filewri = new FileWriter( "/usr/local/forseti/log/SLDS-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-hh-mm") + ".log", true); PrintWriter pw = new PrintWriter(filewri); for (int i = 0; i < BASES.size(); i++) { String nombre = (String) BASES.get(i); pw.println("----------------------------------------------------------------------------"); pw.println(" " + "ACTUALIZANDO LA BASE DE DATOS: " + nombre + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")); pw.println("----------------------------------------------------------------------------"); pw.flush(); System.out.println("ACTUALIZANDO LA BASE DE DATOS: " + nombre + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")); //Empieza por la de saldos con = JAccesoBD.getConexion(nombre); String sql[] = { "select * from sp_invserv_actualizar_existencias() as ( err integer, res varchar ) ", "select * from sp_prod_formulas_actualizar_niveles() as ( err integer, res varchar ) ", "select * from sp_invserv_actualizar_sdos() as ( err integer, res varchar ) ", "select * from sp_invserv_actualizar_polcant() as ( err integer, res varchar ) ", "select * from sp_cont_catalogo_actualizar_sdos() as ( err integer, res varchar ) ", "select * from sp_bancos_actualizar_sdos() as ( err integer, res varchar ) ", "select * from sp_provee_actualizar_sdos() as ( err integer, res varchar ) ", "select * from sp_client_actualizar_sdos() as ( err integer, res varchar ) " }; try { Statement s = con.createStatement(); for (int j = 0; j < sql.length; j++) { System.out.println("EJECUTANDO: " + sql[j]); pw.println("EJECUTANDO: " + sql[j] + "\n"); pw.flush(); ResultSet rs = s.executeQuery(sql[j]); if (rs.next()) { res = rs.getShort("ERR"); mensaje = rs.getString("RES"); } //outprintln("REGRESO: ERR: " + res + " RES: " + mensaje + " " + JUtil.obtFechaTxt(new Date(), "hh:mm:ss")); pw.println("REGRESO: ERR: " + res + " RES: " + mensaje + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")); pw.flush(); } s.close(); } catch (NullPointerException e) //Se captura cuando no existe una base de datos fsica pero el cabecero general de tbl_bd contiene una { System.out.println(e.toString()); pw.println(e.toString() + "\n"); pw.flush(); } catch (SQLException e) { System.out.println(e.toString()); pw.println(e.toString() + "\n"); pw.flush(); } finally { JAccesoBD.liberarConexion(con); } } // Fin for BA>SES pw.println("----------------------------- FIN DE LA ACTUALIZACION ----------------------------------"); pw.flush(); idsalida = 0; } catch (IOException e) { idsalida = 3; salida += "OCURRIERON ERRORES AL ABRIR O COPIAR ARCHIVOS... REVISA EL REGISTRO DE ACTUALIZACIONES<br>"; e.printStackTrace(); } }
From source file:de.clusteval.tools.ClustQualityEval.java
public ClustQualityEval(final String absRepoPath, final String dataConfigName, final String... qualityMeasures) throws RepositoryAlreadyExistsException, InvalidRepositoryException, RepositoryConfigNotFoundException, RepositoryConfigurationException, UnknownClusteringQualityMeasureException, InterruptedException, UnknownDataSetFormatException, UnknownGoldStandardFormatException, GoldStandardNotFoundException, GoldStandardConfigurationException, DataSetConfigurationException, DataSetNotFoundException, DataSetConfigNotFoundException, GoldStandardConfigNotFoundException, NoDataSetException, DataConfigurationException, DataConfigNotFoundException, NumberFormatException, RunResultParseException, ConfigurationException, RegisterException, UnknownContextException, UnknownParameterType, IOException, UnknownRunResultFormatException, InvalidRunModeException, UnknownParameterOptimizationMethodException, NoOptimizableProgramParameterException, UnknownProgramParameterException, InvalidConfigurationFileException, NoRepositoryFoundException, InvalidOptimizationParameterException, RunException, UnknownDataStatisticException, UnknownProgramTypeException, UnknownRProgramException, IncompatibleParameterOptimizationMethodException, UnknownDistanceMeasureException, UnknownRunStatisticException, UnknownDataSetTypeException, UnknownRunDataStatisticException, UnknownDataPreprocessorException, IncompatibleDataSetConfigPreprocessorException, IncompatibleContextException, InvalidDataSetFormatVersionException, RNotAvailableException, FormatConversionException {/*from w w w .ja v a 2 s. co m*/ super(); ClustevalBackendServer.logLevel(Level.INFO); ClustevalBackendServer.getBackendServerConfiguration().setNoDatabase(true); ClustevalBackendServer.getBackendServerConfiguration().setCheckForRunResults(false); this.log = LoggerFactory.getLogger(this.getClass()); final Repository parent = new Repository( new File(absRepoPath).getParentFile().getParentFile().getAbsolutePath(), null); parent.initialize(); this.repo = new RunResultRepository(absRepoPath, parent); this.repo.initialize(); List<ParameterOptimizationResult> result = new ArrayList<ParameterOptimizationResult>(); final ParameterOptimizationRun run = (ParameterOptimizationRun) ParameterOptimizationResult .parseFromRunResultFolder(parent, new File(absRepoPath), result, false, false, false); this.dataConfig = this.repo.getStaticObjectWithName(DataConfig.class, dataConfigName); final List<ClusteringQualityMeasure> measures = new ArrayList<ClusteringQualityMeasure>(); if (qualityMeasures.length == 0) { log.error("Please add at least one quality measure to the command line arguments."); this.repo.terminateSupervisorThread(); return; } for (String measureSimpleName : qualityMeasures) { measures.add(ClusteringQualityMeasure.parseFromString(this.repo, measureSimpleName)); } Set<Thread> threads = new HashSet<Thread>(); System.out.println("Program configurations:"); System.out.println(run.getProgramConfigs()); for (final ProgramConfig pc : run.getProgramConfigs()) { // get the dataset for this program config DataSet dsIn = Parser.parseFromFile(DataSet.class, new File(FileUtils.buildPath(absRepoPath, "inputs", pc.toString() + "_" + dataConfig.toString(), dataConfig.getDatasetConfig().getDataSet().getMajorName(), dataConfig.getDatasetConfig().getDataSet().getMinorName()))); // get dataset in standard format final DataSet ds = dsIn.preprocessAndConvertTo(run.getContext(), run.getContext().getStandardInputFormat(), dataConfig.getDatasetConfig().getConversionInputToStandardConfiguration(), dataConfig.getDatasetConfig().getConversionStandardToInputConfiguration()); ds.loadIntoMemory(); Thread t = new Thread() { public void run() { try { DataConfig dc = dataConfig.clone(); dc.getDatasetConfig().setDataSet(ds); File f = new File(FileUtils.buildPath(repo.getBasePath(), "clusters")); File[] childs = f.listFiles(new FilenameFilter() { /* * (non-Javadoc) * * @see java.io.FilenameFilter#accept(java.io.File, * java.lang.String) */ @Override public boolean accept(File dir, String name) { return name.startsWith(pc.getName() + "_" + dataConfig.getName()) && name.endsWith(".results.conv"); } }); // printer = new MyProgressPrinter(childs.length, true); ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)) .info("Assessing qualities of clusterings ..."); final Map<Long, ClusteringQualitySet> qualsMap = new HashMap<Long, ClusteringQualitySet>(); for (File clusteringFile : childs) { try { Clustering cl = Clustering .parseFromFile(repo, clusteringFile.getAbsoluteFile(), true).getSecond(); // only recalculate for those, for which the // measure // hasn't // been evaluated List<ClusteringQualityMeasure> toEvaluate = new ArrayList<ClusteringQualityMeasure>( measures); try { if (cl.getQualities() != null) toEvaluate.removeAll(cl.getQualities().keySet()); } catch (NullPointerException e) { System.out.println(clusteringFile); throw e; } ClusteringQualitySet quals = new ClusteringQualitySet(); // evaluate the new quality measures if (!toEvaluate.isEmpty()) { quals.putAll(cl.assessQuality(dc, toEvaluate)); System.out.println(quals); // write the new qualities into the // results.qual // file for (ClusteringQualityMeasure m : quals.keySet()) FileUtils.appendStringToFile( clusteringFile.getAbsolutePath().replaceFirst(".results.conv", ".results.qual"), String.format("%s\t%s", m.toString(), quals.get(m).getValue()) + "\n"); } long iterationNumber = Long.parseLong(clusteringFile.getName() .replaceFirst(String.format("%s_%s.", pc.toString(), dc.toString()), "") .replaceFirst(".results.conv", "")); // store all qualities of the clustering in one // set ClusteringQualitySet allQuals = new ClusteringQualitySet(); if (cl.getQualities() != null) allQuals.putAll(cl.getQualities()); allQuals.putAll(quals); qualsMap.put(iterationNumber, allQuals); } catch (IOException e) { e.printStackTrace(); } catch (UnknownGoldStandardFormatException e) { e.printStackTrace(); } catch (UnknownDataSetFormatException e) { e.printStackTrace(); } catch (InvalidDataSetFormatVersionException e) { e.printStackTrace(); } } // update complete quality file // we want to have the same lines conserving the same NT // and // skipped // iterations infos (missing lines), therefore we parse // the // old file // first, iterate over all lines and write the same // lines // but add // the additional infos (if there are any) TextFileParser parser = new TextFileParser( FileUtils.buildPath(repo.getBasePath(), "clusters", String.format("%s_%s.results.qual.complete", pc.toString(), dc.toString())), new int[0], new int[0], FileUtils.buildPath(repo.getBasePath(), "clusters", String .format("%s_%s.results.qual.complete.new", pc.toString(), dc.toString())), OUTPUT_MODE.STREAM) { protected List<ClusteringQualityMeasure> measures; /* * (non-Javadoc) * * @see * utils.parse.TextFileParser#processLine(java.lang. * String[], java.lang.String[]) */ @Override protected void processLine(String[] key, String[] value) { } /* * (non-Javadoc) * * @see * utils.parse.TextFileParser#getLineOutput(java * .lang .String[], java.lang.String[]) */ @Override protected String getLineOutput(String[] key, String[] value) { StringBuffer sb = new StringBuffer(); // sb.append(combineColumns(value)); sb.append(combineColumns(Arrays.copyOf(value, 2))); if (currentLine == 0) { sb.append(outSplit); sb.append(combineColumns(Arrays.copyOfRange(value, 2, value.length))); measures = new ArrayList<ClusteringQualityMeasure>(); for (int i = 2; i < value.length; i++) try { measures.add( ClusteringQualityMeasure.parseFromString(parent, value[i])); } catch (UnknownClusteringQualityMeasureException e) { e.printStackTrace(); this.terminate(); } // get measures, which are not in the // complete // file // header if (qualsMap.keySet().iterator().hasNext()) { Set<ClusteringQualityMeasure> requiredMeasures = qualsMap .get(qualsMap.keySet().iterator().next()).keySet(); requiredMeasures.removeAll(measures); for (ClusteringQualityMeasure m : requiredMeasures) { sb.append(outSplit); sb.append(m.toString()); } measures.addAll(requiredMeasures); } } else if (value[0].contains("*")) { // do nothing } else { long iterationNumber = Long.parseLong(value[0]); ClusteringQualitySet quals = qualsMap.get(iterationNumber); boolean notTerminated = value[3].equals("NT"); // for (int i = value.length - 2; i < // measures // .size(); i++) { // sb.append(outSplit); // if (notTerminated) // sb.append("NT"); // else // sb.append(quals.get(measures.get(i))); // } for (int i = 0; i < measures.size(); i++) { sb.append(outSplit); if (notTerminated) sb.append("NT"); else if (quals.containsKey(measures.get(i))) sb.append(quals.get(measures.get(i))); else sb.append(value[i + 2]); } } sb.append(System.getProperty("line.separator")); return sb.toString(); } }; try { parser.process(); } catch (Exception e) { e.printStackTrace(); } ds.unloadFromMemory(); } catch (Exception e) { e.printStackTrace(); } } }; threads.add(t); t.start(); } // add the new clustering quality measures into the run config file TextFileParser p = new TextFileParser(run.getAbsolutePath(), null, null, false, "", run.getAbsolutePath() + ".new", OUTPUT_MODE.STREAM) { /* * (non-Javadoc) * * @see utils.parse.TextFileParser#processLine(java.lang.String[], * java.lang.String[]) */ @Override protected void processLine(String[] key, String[] value) { } /* * (non-Javadoc) * * @see utils.parse.TextFileParser#getLineOutput(java.lang.String[], * java.lang.String[]) */ @Override protected String getLineOutput(String[] key, String[] value) { StringBuilder sb = new StringBuilder(); sb.append(value[0]); if (value[0].contains("qualityMeasures = ")) for (ClusteringQualityMeasure m : measures) if (!value[0].contains(m.toString())) { sb.append(","); sb.append(m.toString()); } sb.append(System.getProperty("line.separator")); return sb.toString(); } }.process(); for (Thread t : threads) t.join(); System.exit(0); }
From source file:net.cbtltd.rest.interhome.A_Handler.java
/** * Read prices./*from www . ja v a 2 s .c om*/ * * @param version the version * @param salesoffice the salesoffice * @param currency the currency * @param duration the duration */ private synchronized void readPrices(Date version, String salesoffice, Currency.Code currency, int duration) { String altparty = getAltpartyid(); String message = "Interhome readPrices Weekly " + altparty; LOG.debug(message); String fn = null; final SqlSession sqlSession = RazorServer.openSession(); try { JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.price"); Unmarshaller um = jc.createUnmarshaller(); fn = "price_" + salesoffice + "_" + currency.name().toLowerCase() + (duration < 14 ? "" : "_" + String.valueOf(duration)) + ".xml"; Prices prices = (Prices) um.unmarshal(ftp(fn)); if (prices != null && prices.getPrice() != null) { int count = prices.getPrice().size(); LOG.debug("Total prices for " + duration + " days: " + count); } else { LOG.debug("Error, no price file for " + duration + " days"); return; } int i = 0; for (Price weekprice : prices.getPrice()) { String altid = weekprice.getCode(); // if (!altid.equals("CH3920.126.1") || !"CH3920.126.1".equalsIgnoreCase(altid)) continue; String productid = getProductId(altid); if (productid == null) { Product product = sqlSession.getMapper(ProductMapper.class) .altread(new NameId(altparty, altid)); if (product == null) { LOG.error(Error.product_id.getMessage() + " " + weekprice.getCode()); continue; } PRODUCTS.put(altid, product.getId()); productid = getProductId(altid); } // if (!productid.equals("27077") || !String.valueOf(27077).equalsIgnoreCase(productid)) continue; Date fromdate = weekprice.getStartdate().toGregorianCalendar().getTime(); Date todate = weekprice.getEnddate().toGregorianCalendar().getTime(); if (weekprice.getServices() != null && weekprice.getServices().getService() != null) { net.cbtltd.shared.Price mandatory = new net.cbtltd.shared.Price(); mandatory.setEntitytype(NameId.Type.Mandatory.name()); mandatory.setEntityid(productid); mandatory.setCurrency(currency.name()); mandatory.setPartyid(altparty); mandatory.setVersion(version); for (Service service : weekprice.getServices().getService()) { mandatory.setType("Fees"); mandatory.setDate(fromdate); mandatory.setTodate(todate); mandatory.setQuantity(0.0); mandatory.setUnit(Unit.EA); mandatory.setAvailable(1); mandatory.setMinStay(1); net.cbtltd.shared.Price existprice = sqlSession.getMapper(PriceMapper.class) .exists(mandatory); if (existprice == null) { sqlSession.getMapper(PriceMapper.class).create(mandatory); } else { mandatory = existprice; } mandatory.setState(net.cbtltd.shared.Price.CREATED); mandatory.setName(getServicename(service.getCode())); mandatory.setMinimum(0.0); mandatory.setValue( service.getServiceprice() == null ? 0.0 : service.getServiceprice().doubleValue()); mandatory.setRule("Manual"); sqlSession.getMapper(PriceMapper.class).update(mandatory); } sqlSession.getMapper(PriceMapper.class).cancelversion(mandatory); } // Adjustment adjustment = setAdjustment(sqlSession, productid, 7, 7, currency.name(), fromdate, todate, weekprice, "1111111", "week", version); Adjustment action = new Adjustment(); action.setCurrency(currency.name()); action.setState(Adjustment.Created); action.setPartyID(altparty); action.setProductID(productid); action.setFromDate(fromdate); action.setToDate(todate); action.setMaxStay(999); action.setMinStay(5); Adjustment example = sqlSession.getMapper(AdjustmentMapper.class).readbyexample(action); if (example == null) continue; Double rentalPrice; if (weekprice.getSpecialoffer() != null && weekprice.getSpecialoffer().getSpecialofferprice() != null) { rentalPrice = weekprice.getSpecialoffer().getSpecialofferprice().doubleValue(); } else { rentalPrice = weekprice.getRentalprice().doubleValue(); } Double dailyprice = DAILYPRICES.get(example.getID()); Double fixprice = example.getFixPrice(); Double extra = ((rentalPrice - fixprice) / duration) - dailyprice;// ( ( weekprice - fixprice ) / 7 ) - rentalprice[per/day] action.setMinStay(duration); action.setMaxStay(duration); action.setState(null); net.cbtltd.shared.Adjustment exists = sqlSession.getMapper(AdjustmentMapper.class).exists(action); if (exists == null) { sqlSession.getMapper(AdjustmentMapper.class).create(action); } else { action = exists; } action.setExtra(PaymentHelper.getAmountWithTwoDecimals(extra)); action.setServicedays(Adjustment.WEEK); action.setState(Adjustment.Created); action.setFixPrice(fixprice); action.setVersion(version); sqlSession.getMapper(AdjustmentMapper.class).update(action); sqlSession.getMapper(AdjustmentMapper.class).cancelversion(action); LOG.debug(i++ + " WeekPrice: " + " " + weekprice.getCode() + " " + productid + " " + salesoffice + " " + action.getExtra() + " " + currency + " " + duration); } sqlSession.commit(); } catch (NullPointerException ex) { ex.printStackTrace(); LOG.error("NPE" + ex.getStackTrace()); sqlSession.rollback(); } catch (RuntimeException e) { e.printStackTrace(); LOG.error("RuntimeExc " + e.getStackTrace()); sqlSession.rollback(); } catch (Throwable x) { sqlSession.rollback(); LOG.error(x.getClass().getName() + ": " + x.getMessage()); } finally { sqlSession.close(); delete(fn); } }
From source file:jdbc.pool.JDBCPoolTestCase.java
public void testGetPoolStatistics() { try {// w w w .j a v a2s . c om CConnectionPoolManager manager = null; manager = create(); try { manager.getPoolStatistics("ORACLE"); } catch (NullPointerException e) { assertTrue("Pool attribute load-on-startup is false", true); } CPoolStatisticsBean bean = manager.getPoolStatistics("MYSQL"); assertEquals("MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 0, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); // assertEquals("Connections Closed Count", 0, bean.getNoOfConnectionsClosed()); // assertEquals("Connections Created Count", 0, bean.getNoOfConnectionsCreated()); // assertEquals("Connections Locked", 0, bean.getNoOfConnectionsLocked()); // assertEquals("Connections Requested Count", 0, bean.getNoOfConnectionsRequested()); // assertEquals("Connections Unlocked Count", 0, bean.getNoOfConnectionsUnlocked()); // assertEquals("New Connections Created Count", 0, bean.getNoOfNewConnectionsRequested()); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } }
From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java
public void testGetPoolStatistics() { testGetInstanceNull();//from ww w . ja v a2 s .com System.out.println("testGetPoolStatistics started"); try { CConnectionPoolManager manager = null; manager = create(); try { manager.getPoolStatistics("ORACLE"); } catch (NullPointerException e) { assertTrue("Pool attribute load-on-startup is false", true); } CPoolStatisticsBean bean = manager.getPoolStatistics("MYSQL"); assertEquals("MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 0, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); // assertEquals("Connections Closed Count", 0, bean.getNoOfConnectionsClosed()); // assertEquals("Connections Created Count", 0, bean.getNoOfConnectionsCreated()); // assertEquals("Connections Locked", 0, bean.getNoOfConnectionsLocked()); // assertEquals("Connections Requested Count", 0, bean.getNoOfConnectionsRequested()); // assertEquals("Connections Unlocked Count", 0, bean.getNoOfConnectionsUnlocked()); // assertEquals("New Connections Created Count", 0, bean.getNoOfNewConnectionsRequested()); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } System.out.println("testGetPoolStatistics() end"); }
From source file:com.surevine.alfresco.repo.action.AssignRandomValidSecurityGroupsAction.java
@Override protected void executeImpl(final Action action, final NodeRef nodeRef) { try {//from w w w .j a va 2s.co m //First things first, set a modifier for this item. We try to round-robin all the users //This is intended to be run against an item without any security groups assigned. If run against //an item that already has security groups assigned, it will not consider that the selected user may //not be able to access the item, and will throw an AccessDenied exception accordingly Iterator<NodeRef> peopleNodes = _personService.getAllPeople().iterator(); int skipCount = 0; while (peopleNodes.hasNext()) { NodeRef personNode = peopleNodes.next(); if (!(skipCount++ < _userIndexOffset)) { String userName = _nodeService.getProperty(personNode, ContentModel.PROP_USERNAME).toString(); if (LOG.isInfoEnabled()) { LOG.info("Setting modifier of " + nodeRef + " to " + userName); } AuthenticationUtil.runAs(new ModifyItemWork(nodeRef), userName); if (!peopleNodes.hasNext()) { _userIndexOffset = 0; } else { _userIndexOffset++; } break; } } ; // First, get the list of everyone to have modified this item - we // need to make sure all // these users could have seen the security marking we will // generate, to ensure // consistency (actually, we could be more specific than this if we // needed to as what we // actually need to ensure is that a user who can see Version X can // see all versions <X) Object o = _nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER); if (o == null) { o = _nodeService.getProperty(nodeRef, ContentModel.PROP_CREATOR); } final String owner = o.toString(); Collection<String> modifiers = new HashSet<String>(1); try { Iterator<Version> allVersions = _versionService.getVersionHistory(nodeRef).getAllVersions() .iterator(); while (allVersions.hasNext()) { Version v = allVersions.next(); if (LOG.isDebugEnabled()) { LOG.debug("Adding " + v.getFrozenModifier() + " to the list of modifiers for " + nodeRef); } modifiers.add(v.getFrozenModifier()); } } catch (NullPointerException e) { // This means that the item isn't versionable, in which case use // the current modifier modifiers.add(owner); } Iterator<String> modifierUserNames; // For each security Group, work out the groups to assign for (int i = 0; i < _constraintNames.length; i++) { modifierUserNames = modifiers.iterator(); Set<String> potentialGroups = null; while (modifierUserNames.hasNext()) { String userName = modifierUserNames.next(); if (potentialGroups == null) { potentialGroups = new HashSet<String>(AuthenticationUtil .runAs(new GetGivenUserSecurityMarkingsWork(_constraintNames[i]), userName)); } else { potentialGroups.retainAll(AuthenticationUtil .runAs(new GetGivenUserSecurityMarkingsWork(_constraintNames[i]), userName)); } } Iterator<String> potentialGroupsIt = potentialGroups.iterator(); ArrayList<String> groupsToAdd = new ArrayList<String>(2); while (potentialGroupsIt.hasNext()) { String potentialGroup = potentialGroupsIt.next(); if (LOG.isDebugEnabled()) { LOG.debug(potentialGroup + " is a potential group for " + nodeRef); } if (_randomiser.nextFloat() < _chanceToApplyGivenSecurityGroup) { if (LOG.isInfoEnabled()) { LOG.info("Adding " + potentialGroup + " to " + nodeRef); } groupsToAdd.add(potentialGroup); } } if (groupsToAdd.contains("ATOMAL2") && !groupsToAdd.contains("ATOMAL1")) { groupsToAdd.add("ATOMAL1"); } QName propertyQName = getQNameFromConstraintName(_constraintNames[i]); if (groupsToAdd.size() > 0) { if (LOG.isDebugEnabled()) { LOG.debug("Making modification as " + owner); } //Parts of the renditioned aspects, which require us to have privs to previews etc, require this to be run as the last modifier of the document AuthenticationUtil.runAs(new ModifySecurityMarkingWork(nodeRef, propertyQName, groupsToAdd), owner); } } //OK, now we've set the security groups - we are now going to munge the modifier of the item /* * * This bit seems to: * A) Break whichever site you run it against * B) Not consider whether the selected user could actually access the node they are trying to update * */ } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }