List of usage examples for java.lang NullPointerException printStackTrace
public void printStackTrace()
From source file:org.opendatakit.aggregate.odktables.DataManager.java
/** * Delete a row./*from www. j av a 2 s . c o m*/ * * @param rowId * the row to delete. * @param currentRowETag * the ETag for that row, as known to the requester * @return returns the new dataETag that is current after deleting the row. * @throws ODKEntityNotFoundException * if there is no row with the given id in the datastore * @throws ODKDatastoreException * @throws ODKTaskLockException * @throws PermissionDeniedException * @throws InconsistentStateException * @throws BadColumnNameException * @throws ETagMismatchException */ public String deleteRow(String rowId, String currentRowETag) throws ODKEntityNotFoundException, ODKDatastoreException, ODKTaskLockException, PermissionDeniedException, InconsistentStateException, BadColumnNameException, ETagMismatchException { try { Validate.notNull(rowId); Validate.notBlank(rowId); userPermissions.checkPermission(appId, tableId, TablePermission.DELETE_ROW); String dataETagAtModification = null; LockTemplate propsLock = new LockTemplate(tableId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, cc); try { propsLock.acquire(); Sequencer sequencer = new Sequencer(cc); DbTableEntryEntity entry = DbTableEntry.getTableIdEntry(tableId, cc); String schemaETag = entry.getSchemaETag(); if (schemaETag == null) { throw new InconsistentStateException("Schema for table " + tableId + " is not yet defined."); } DbTableDefinitionsEntity tableDefn = DbTableDefinitions.getDefinition(tableId, schemaETag, cc); List<DbColumnDefinitionsEntity> columns = DbColumnDefinitions.query(tableId, schemaETag, cc); DbTable table = DbTable.getRelation(tableDefn, columns, cc); DbLogTable logTable = DbLogTable.getRelation(tableDefn, columns, cc); revertPendingChanges(entry, columns, table, logTable); Entity entity = table.getEntity(rowId, cc); // entity exists (or we would have thrown an // ODKEntityNotFoundException). String serverRowETag = entity.getString(DbTable.ROW_ETAG); if (!currentRowETag.equals(serverRowETag)) { // if null, then the client thinks they are creating a new row. // The rows may be identical, but leave that to the client to // determine // trigger client-side conflict resolution. // Otherwise, if there is a mis-match, then the client needs to pull // and // perform client-side conflict resolution on the changes already up // on the server. throw new ETagMismatchException(String.format("rowETag %s does not match %s " + "for rowId %s", currentRowETag, serverRowETag, rowId)); } Scope scope = converter.getDbTableFilterScope(entity); // check for read access boolean hasPermissions = false; if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_READ)) { hasPermissions = true; } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.READ_ROW, rowId, scope)) { hasPermissions = true; } if (!hasPermissions) { throw new PermissionDeniedException( String.format("Denied table %s row %s read access to user %s", tableId, rowId, userPermissions.getOdkTablesUserId())); } // check for delete access hasPermissions = false; if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_DELETE)) { hasPermissions = true; } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.DELETE_ROW, rowId, scope)) { hasPermissions = true; } if (!hasPermissions) { throw new PermissionDeniedException( String.format("Denied table %s row %s delete access to user %s", tableId, rowId, userPermissions.getOdkTablesUserId())); } // get new dataETag dataETagAtModification = PersistenceUtils.newUri(); entry.setPendingDataETag(dataETagAtModification); entry.put(cc); // remember the previous row ETag so we can chain revisions in the // DbLogTable String previousRowETag = entity.getString(DbTable.ROW_ETAG); // update the row ETag and deletion status entity.set(DbTable.ROW_ETAG, PersistenceUtils.newUri()); entity.set(DbTable.DELETED, true); // create log table entry Entity logEntity = creator.newLogEntity(logTable, dataETagAtModification, previousRowETag, entity, columns, sequencer, cc); // commit the log change to the database (must be done first!) DbLogTable.putEntity(logEntity, cc); // commit the row change DbTable.putEntity(entity, cc); // NOTE: the DbTableInstanceFiles objects are never deleted unless the // table is dropped. // They hold the file attachments and are eferred to by the records in // the DbLogTable // even if the row is deleted from the set of active records (i.e., // DbTable). // update the TableEntry to reflect the completion of the change entry.setDataETag(entry.getPendingDataETag()); entry.setPendingDataETag(null); entry.put(cc); } finally { propsLock.release(); } return dataETagAtModification; } catch (NullPointerException e) { e.printStackTrace(); throw e; } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); throw e; } catch (ODKEntityPersistException e) { e.printStackTrace(); throw e; } catch (ODKEntityNotFoundException e) { e.printStackTrace(); throw e; } catch (ETagMismatchException e) { e.printStackTrace(); throw e; } catch (ODKDatastoreException e) { e.printStackTrace(); throw e; } catch (ODKTaskLockException e) { e.printStackTrace(); throw e; } catch (BadColumnNameException e) { e.printStackTrace(); throw e; } catch (PermissionDeniedException e) { e.printStackTrace(); throw e; } catch (InconsistentStateException e) { e.printStackTrace(); throw e; } }
From source file:org.opendatakit.odktables.DataManager.java
/** * Retrieve a row from the table.//from w ww. ja v a 2 s . c o m * * @param rowId * the id of the row * @return the row * @throws ODKEntityNotFoundException * if the row with the given id does not exist * @throws ODKDatastoreException * @throws PermissionDeniedException * @throws InconsistentStateException * @throws ODKTaskLockException * @throws BadColumnNameException */ public Row getRow(String rowId) throws ODKEntityNotFoundException, ODKDatastoreException, PermissionDeniedException, InconsistentStateException, ODKTaskLockException, BadColumnNameException { try { Validate.notEmpty(rowId); userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW); List<DbColumnDefinitionsEntity> columns = null; Entity entity = null; OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.SHORT, cc); try { propsLock.acquire(); DbTableEntryEntity entry = DbTableEntry.getTableIdEntry(tableId, cc); String schemaETag = entry.getSchemaETag(); if (schemaETag == null) { throw new InconsistentStateException("Schema for table " + tableId + " is not yet defined."); } DbTableDefinitionsEntity tableDefn = DbTableDefinitions.getDefinition(tableId, schemaETag, cc); columns = DbColumnDefinitions.query(tableId, schemaETag, cc); DbTable table = DbTable.getRelation(tableDefn, columns, cc); DbLogTable logTable = DbLogTable.getRelation(tableDefn, columns, cc); revertPendingChanges(entry, columns, table, logTable); entity = table.getEntity(rowId, cc); } finally { propsLock.release(); } if (columns == null) { throw new InconsistentStateException("Unable to retrieve rows for table " + tableId + "."); } Row row = converter.toRow(entity, columns); if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_READ)) { return row; } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.READ_ROW, row.getRowId(), /* row.getFilterScope() */ Scope.EMPTY_SCOPE)) { return row; } throw new PermissionDeniedException(String.format("Denied table %s row %s access to user %s", tableId, rowId, userPermissions.getOdkTablesUserId())); } catch (NullPointerException e) { e.printStackTrace(); throw e; } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); throw e; } catch (ODKEntityPersistException e) { e.printStackTrace(); throw e; } catch (ODKEntityNotFoundException e) { e.printStackTrace(); throw e; } catch (ODKDatastoreException e) { e.printStackTrace(); throw e; } catch (ODKTaskLockException e) { e.printStackTrace(); throw e; } catch (BadColumnNameException e) { e.printStackTrace(); throw e; } catch (PermissionDeniedException e) { e.printStackTrace(); throw e; } catch (InconsistentStateException e) { e.printStackTrace(); throw e; } }
From source file:marytts.tools.voiceimport.HMMVoicePackager.java
@Override protected HashMap<String, File> getVoiceDataFiles() { try {/*from ww w . j a va 2 s . c o m*/ File in, out; String rootDir = db.getProp(db.ROOTDIR); HashMap<String, File> files = new HashMap<String, File>(); // Before setting the tree files, we need to check if they contain aliases for the extra features used for training // if so there must be a file mary/hmmFeaturesMap.txt which has to be used to convert back the feature names // Check if features map was used System.out.println("Checking if aliases for extra features used for training were used"); File featuresMap = new File(rootDir + getProp(hmmFeaturesMapFile)); if (featuresMap.exists()) { // convert back the features in all tree files: treeDurFile, treeLf0File, treeMcpFile, treeStrFile loadFeaturesMap(rootDir + getProp(hmmFeaturesMapFile)); replaceBackFeatureNames(rootDir + getProp(treeDurFile)); replaceBackFeatureNames(rootDir + getProp(treeLf0File)); replaceBackFeatureNames(rootDir + getProp(treeMcpFile)); replaceBackFeatureNames(rootDir + getProp(treeStrFile)); } in = new File(rootDir + getProp(treeDurFile)); files.put(treeDurFile, in); in = new File(rootDir + getProp(treeLf0File)); files.put(treeLf0File, in); in = new File(rootDir + getProp(treeMcpFile)); files.put(treeMcpFile, in); /* optional file for mixed excitation */ in = new File(rootDir + getProp(treeStrFile)); if (in.exists()) { files.put(treeStrFile, in); } in = new File(rootDir + getProp(pdfDurFile)); files.put(pdfDurFile, in); in = new File(rootDir + getProp(pdfLf0File)); files.put(pdfLf0File, in); in = new File(rootDir + getProp(pdfMcpFile)); files.put(pdfMcpFile, in); in = new File(rootDir + getProp(pdfStrFile)); if (in.exists()) { files.put(pdfStrFile, in); } /* global variance files */ in = new File(rootDir + getProp(pdfMcpGVFile)); if (in.exists()) { files.put(pdfMcpGVFile, in); } in = new File(rootDir + getProp(pdfLf0GVFile)); if (in.exists()) { files.put(pdfLf0GVFile, in); } in = new File(rootDir + getProp(pdfStrGVFile)); if (in.exists()) { files.put(pdfStrGVFile, in); } in = new File(rootDir + getProp(mixFiltersFile)); files.put(mixFiltersFile, in); // if there is a trickyPhones file in = new File(rootDir + getProp(trickyPhonesFile)); if (in.exists()) { files.put(trickyPhonesFile, in); trickyPhones = true; } if ("true".equals(getProp(vocalizationSupport))) { String[] vocalizationProperties = { "VocalizationFeatureFileWriter.featureDefinition", "VocalizationFeatureFileWriter.featureFile", "VocalizationUnitfileWriter.unitFile", "VocalizationIntonationWriter.intonationTimeLineFile", "VocalizationIntonationWriter.intonationFeatureDefinition", "MLSAFeatureFileWriter.mlsaOutputFile" }; for (String property : vocalizationProperties) { String fileName; try { fileName = db.getProperty(property); } catch (NullPointerException e) { throw e; } File file = new File(fileName); files.put(property, file); } } /* copy one example of MARY context features file, it can be one of the * files used for testing in phonefeatures/*.pfeats*/ File dirPhonefeatures = new File(rootDir + "phonefeatures/"); if (dirPhonefeatures.exists() && dirPhonefeatures.list().length > 0) { String[] feaFiles = dirPhonefeatures.list(); in = new File(rootDir + "phonefeatures/" + feaFiles[0]); //out = new File(newVoiceDir + getFileName(feaFiles[0])); //FileUtils.copy(in,out); files.put(FeaFile, in); featuresFileExample = rootDir + "phonefeatures/" + feaFiles[0]; } else { System.out.println( "Problem copying one example of context features, the directory phonefeatures/ is empty or directory does not exist."); throw new IOException(); } return files; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.opendatakit.odktables.DataManager.java
/** * Delete a row.// w w w .j a va 2 s . c o m * * @param rowId * the row to delete. * @param currentRowETag * the ETag for that row, as known to the requester * @return returns the new dataETag that is current after deleting the row. * @throws ODKEntityNotFoundException * if there is no row with the given id in the datastore * @throws ODKDatastoreException * @throws ODKTaskLockException * @throws PermissionDeniedException * @throws InconsistentStateException * @throws BadColumnNameException * @throws ETagMismatchException */ public String deleteRow(String rowId, String currentRowETag) throws ODKEntityNotFoundException, ODKDatastoreException, ODKTaskLockException, PermissionDeniedException, InconsistentStateException, BadColumnNameException, ETagMismatchException { try { Validate.notNull(rowId); Validate.notBlank(rowId); userPermissions.checkPermission(appId, tableId, TablePermission.DELETE_ROW); String dataETagAtModification = null; OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.SHORT, cc); try { propsLock.acquire(); Sequencer sequencer = new Sequencer(cc); DbTableEntryEntity entry = DbTableEntry.getTableIdEntry(tableId, cc); String schemaETag = entry.getSchemaETag(); if (schemaETag == null) { throw new InconsistentStateException("Schema for table " + tableId + " is not yet defined."); } DbTableDefinitionsEntity tableDefn = DbTableDefinitions.getDefinition(tableId, schemaETag, cc); List<DbColumnDefinitionsEntity> columns = DbColumnDefinitions.query(tableId, schemaETag, cc); DbTable table = DbTable.getRelation(tableDefn, columns, cc); DbLogTable logTable = DbLogTable.getRelation(tableDefn, columns, cc); revertPendingChanges(entry, columns, table, logTable); Entity entity = table.getEntity(rowId, cc); // entity exists (or we would have thrown an // ODKEntityNotFoundException). String serverRowETag = entity.getString(DbTable.ROW_ETAG); if (!currentRowETag.equals(serverRowETag)) { // if null, then the client thinks they are creating a new row. // The rows may be identical, but leave that to the client to // determine // trigger client-side conflict resolution. // Otherwise, if there is a mis-match, then the client needs to pull // and // perform client-side conflict resolution on the changes already up // on the server. throw new ETagMismatchException(String.format("rowETag %s does not match %s " + "for rowId %s", currentRowETag, serverRowETag, rowId)); } RowFilterScope rowFilterScope = EntityConverter.getDbTableRowFilterScope(entity); // check for read access boolean hasPermissions = false; if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_READ)) { hasPermissions = true; } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.READ_ROW, rowId, /* scope from dbTable */ Scope.EMPTY_SCOPE)) { hasPermissions = true; } if (!hasPermissions) { throw new PermissionDeniedException( String.format("Denied table %s row %s read access to user %s", tableId, rowId, userPermissions.getOdkTablesUserId())); } // check for delete access hasPermissions = false; if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_DELETE)) { hasPermissions = true; } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.DELETE_ROW, rowId, /* scope from dbTable */ Scope.EMPTY_SCOPE)) { hasPermissions = true; } if (!hasPermissions) { throw new PermissionDeniedException( String.format("Denied table %s row %s delete access to user %s", tableId, rowId, userPermissions.getOdkTablesUserId())); } // get new dataETag dataETagAtModification = PersistenceUtils.newUri(); entry.setPendingDataETag(dataETagAtModification); entry.put(cc); // remember the previous row ETag so we can chain revisions in the // DbLogTable String previousRowETag = entity.getString(DbTable.ROW_ETAG); // update the row ETag and deletion status entity.set(DbTable.ROW_ETAG, PersistenceUtils.newUri()); entity.set(DbTable.DELETED, true); // create log table entry Entity logEntity = creator.newLogEntity(logTable, dataETagAtModification, previousRowETag, entity, columns, sequencer, cc); // commit the log change to the database (must be done first!) DbLogTable.putEntity(logEntity, cc); // commit the row change DbTable.putEntity(entity, cc); // NOTE: the DbTableInstanceFiles objects are never deleted unless the // table is dropped. // They hold the file attachments and are eferred to by the records in // the DbLogTable // even if the row is deleted from the set of active records (i.e., // DbTable). // update the TableEntry to reflect the completion of the change entry.setDataETag(entry.getPendingDataETag()); entry.setPendingDataETag(null); entry.put(cc); } finally { propsLock.release(); } return dataETagAtModification; } catch (NullPointerException e) { e.printStackTrace(); throw e; } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); throw e; } catch (ODKEntityPersistException e) { e.printStackTrace(); throw e; } catch (ODKEntityNotFoundException e) { e.printStackTrace(); throw e; } catch (ETagMismatchException e) { e.printStackTrace(); throw e; } catch (ODKDatastoreException e) { e.printStackTrace(); throw e; } catch (ODKTaskLockException e) { e.printStackTrace(); throw e; } catch (BadColumnNameException e) { e.printStackTrace(); throw e; } catch (PermissionDeniedException e) { e.printStackTrace(); throw e; } catch (InconsistentStateException e) { e.printStackTrace(); throw e; } }
From source file:gov.nih.nci.cbiit.cmts.ws.servlet.AddNewScenario.java
/** ********************************************************** * doPost()// w w w . j a v a2s.c om ************************************************************ */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { path = null; sourceOriginalXSDPath = null; targetOriginalXSDPath = null; mappingFileName = null; tempXSDList = null; alreadyFoundXSDURLList = null; includedXSDList = new ArrayList<String>(); List<String> fileList = new ArrayList<String>(); try { /* disable security for caAdatper 4.3 release 03-31-2009 HttpSession session = req.getSession(false); if(session==null) { res.sendRedirect("/caAdapterWS/login.do"); return; } String user = (String) session.getAttribute("userid"); System.out.println(user); AbstractSecurityDAO abstractDao= DAOFactory.getDAO(); SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess(); Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1); System.out.println(perm); if (!perm.getCreate()){ System.out.println("No create Permission for user" + user); res.sendRedirect("/caAdapterWS/permissionmsg.do"); return; } */ // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> /* FileItem */ items = upload.parseRequest(req); // Process the uploaded items String method = ""; // add, update or delete scenario String scenarioName = null; //mapping scenario name Iterator<FileItem> iter = items.iterator(); String transType = ""; String securityCode = null; String deletionTag = null; List<FileItem> fileItemList = new ArrayList<FileItem>(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String formFieldName = item.getFieldName(); String itemValue = item.getString(); System.out.println( "AddNewScenario.doPost()..item is formField:" + formFieldName + "=" + itemValue); //if (item.getFieldName().equals("jobType")) jobType = item.getString(); if (formFieldName.equals("transformationType")) { transType = itemValue.trim().toLowerCase(); if (transType.startsWith("xq")) transType = "xq"; if (transType.startsWith("xsl")) transType = "xsl"; } if (formFieldName.equals("methd")) { method = itemValue; //System.out.println("AddNewScenario.doPost()..."+formFieldName+":"+method); } if (formFieldName.equals("deleteSecurityCode")) { securityCode = itemValue; ///System.out.println("AddNewScenario.doPost()..."+formFieldName+":"+method); } if (formFieldName.equals("scenarioName")) { scenarioName = itemValue; if ((scenarioName != null) && (!scenarioName.trim().equals(""))) { scenarioName = scenarioName.trim(); String scenarioDeleteTag = "##scenariodelete:"; if (scenarioName.startsWith(scenarioDeleteTag)) { scenarioName = scenarioName.substring(scenarioDeleteTag.length()); String deletionPassword = ""; String scenarioName2 = scenarioName; int iddx = scenarioName.indexOf(":"); if (iddx > 0) { scenarioName2 = scenarioName.substring(0, iddx).trim(); deletionPassword = scenarioName.substring(iddx + 1).trim(); } if (!deletionPassword.trim().equals("")) { deletionTag = deletionPassword; scenarioName = scenarioName2; } else { String errMsg = "Failure : Null Password for scenario deletion"; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } } } else { } } } else fileItemList.add(item); } if ((deletionTag != null) || (method.equalsIgnoreCase("deleteScenario"))) { String errMsg = "Sorry.. Delete scenario is currently not in service."; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } if ((scenarioName == null) || (scenarioName.trim().equals(""))) { String errMsg = "Failure : Scenario Name is Null"; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } scenarioName = scenarioName.trim(); for (char c : scenarioName.toCharArray()) { byte b = (byte) c; int i = (int) b; String bl = null; if ((i >= 97) && (i <= 122)) bl = "" + c; // lowercase alphabetic else if ((i >= 65) && (i <= 90)) bl = "" + c; // uppercase alphabetic else if ((i >= 48) && (i <= 57)) bl = "" + c; // numeric char else if (i == 45) bl = "" + c; // "-" else if (i == 95) bl = "" + c; // "_" if (bl == null) { String errMsg = "Invalid character for scenario name : only alpha-numeric, hypen and underscore. : " + scenarioName; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } } //if (method.equalsIgnoreCase("deleteScenario")) //{ // //} //else { scenarioName = scenarioName.trim(); path = System.getProperty("gov.nih.nci.cbiit.cmts.path"); if (path == null) path = ScenarioUtil.CMTS_SCENARIO_HOME; File scnHome = new File(path); if (!scnHome.exists()) { if (!scnHome.mkdir()) { String errMsg = "Scenario home directory creation failure. Not able to save:" + scenarioName; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } } String scenarioPath = path + File.separator + scenarioName; System.out.println("AddNewScenario.doPost()...scenarioPath:" + scenarioPath); File scenarioDir = null; boolean exists = false; for (File f2 : scnHome.listFiles()) { if (!f2.isDirectory()) continue; String fName = f2.getName(); if (fName.equalsIgnoreCase(scenarioName)) { scenarioDir = f2; exists = true; break; } } //boolean exists = scenarioDir.exists(); //scenarioHomePath = scenarioPath; if (exists) { if ((deletionTag != null) || (method.equalsIgnoreCase("deleteScenario"))) { if ((deletionTag == null) && (securityCode == null)) { String errMsg = "No delete confirmation code for delete scenario:" + scenarioName; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } boolean pass = false; for (File f2 : scenarioDir.listFiles()) { if (!f2.isFile()) continue; String fName = f2.getName(); if ((fName.equalsIgnoreCase( ActionConstants.SCENARIO_DELETE_SECURITY_CONFIRMATION_CODE_FILE)) || (fName.equalsIgnoreCase("password.txt"))) { String tr = FileUtil.readFileIntoString(f2.getAbsolutePath()); if ((tr == null) || (tr.trim().equals(""))) continue; if ((deletionTag != null) && (deletionTag.trim().equals(tr.trim()))) pass = true; if ((securityCode != null) && (securityCode.trim().equals(tr.trim()))) pass = true; } if (pass) break; } if (!pass) { //String daTag = ActionConstants.NEW_ADD_SCENARIO_TAG; //if ((deletionTag != null)&&(deletionTag.trim().equals(daTag))) pass = true; //if ((securityCode != null)&&(securityCode.trim().equals(daTag))) pass = true; } if (!pass) { String errMsg = "Invalid Delete Confirmation Code for delete scenario:" + scenarioName; System.out.println("AddNewScenario.doPost()..Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } boolean deletionSuccess = true; if (deleteFile(scenarioDir)) { try { ScenarioUtil.deleteOneScenarioRegistration(scenarioName); } catch (Exception e1) { deletionSuccess = false; } } else deletionSuccess = false; if (deletionSuccess) res.sendRedirect("successmsg.do?message=" + URLEncoder.encode("Scenario Deletion Success : " + scenarioName, "UTF-8")); else { String errMsg = "Scenario deletion failure:" + scenarioName; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); } return; } else // method value is 'addNewScenario' { //String errMsg="Scenario already exists. Not able to save:"+scenarioName+"<br>If you want to update this scenario. Delete the scenario first."; String errMsg = "Scenario already exists. Not able to save:" + scenarioName; System.out.println("AddNewScenario.doPost()...:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } } else { if ((deletionTag != null) || (method.equalsIgnoreCase("deleteScenario"))) { String errMsg = "This Scenario is NOT exists for deleting:" + scenarioName; System.out.println("AddNewScenario.doPost()...:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } boolean success = (new File(scenarioPath)).mkdir(); if (!success) { String errMsg = "Faild to create scenario:" + scenarioName; System.out.println("AddNewScenario.doPost()...:" + errMsg); req.setAttribute("rtnMessage", errMsg); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } fileList.add(scenarioPath); if ((securityCode == null) || (securityCode.trim().equals(""))) { //String errMsg="Null delete confirmation code: This must be input for delete scenario in the future."; //System.out.println("AddNewScenario.doPost()...Error:"+errMsg); //req.setAttribute("rtnMessage", errMsg); //deleteDirAndFilesOnError(fileList); //res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); //return; } else { String securityCodePath = scenarioPath + File.separator + ActionConstants.SCENARIO_DELETE_SECURITY_CONFIRMATION_CODE_FILE; FileWriter fw = null; try { fw = new FileWriter(securityCodePath); fw.write(securityCode); fw.close(); } catch (Exception ie) { String errMsg = "Delete confirmation Code Saving error."; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } fileList.add(securityCodePath); } String sourcePath = scenarioPath + File.separator + SOURCE_DIRECTORY_TAG; success = (new File(sourcePath)).mkdir(); if (!success) { String errMsg = "Faild to create source schema folder:" + scenarioName; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } fileList.add(sourcePath); String targetPath = scenarioPath + File.separator + TARGET_DIRECTORY_TAG; success = (new File(targetPath)).mkdir(); if (!success) { String errMsg = "Faild to create target schema folder:" + scenarioName; System.out.println("AddNewScenario.doPost()...Error:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } fileList.add(targetPath); } } String pathSourceZip = null; String pathTargetZip = null; boolean instructionFileFound = false; if (fileItemList.size() > 0) { for (FileItem item : fileItemList) { String fieldName = item.getFieldName(); //System.out.println("AddNewScenario.doPost()..item is NOT formField:"+item.getFieldName());//+"="+item.getString()); String filePath = item.getName(); String fileName = extractOriginalFileName(filePath); if (fileName == null || fileName.equals("")) continue; System.out.println("AddNewScenario.doPost()..original file Name:" + fileName + ", Path=" + filePath + ", TransType=" + transType); //System.out.println(" ..original file Path:"+filePath); String tempFileName = fileName; String uploadedFilePath = path + File.separator + scenarioName + File.separator + fileName.toLowerCase(); if (fieldName.equals("mappingFileName")) { System.out.println("AddNewScenario.doPost()...mapping file:" + uploadedFilePath); String uploadedMapBak = uploadedFilePath + ".bak"; //write bak of Mapping file item.write(new File(uploadedMapBak)); int idxT = tempFileName.lastIndexOf("."); if (idxT <= 0) { String errMsg = "This File cannot be identify its file type : " + tempFileName; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } tempFileName = tempFileName.substring(idxT + 1); if (tempFileName.toLowerCase().startsWith(transType.toLowerCase())) { instructionFileFound = true; } else { String errMsg = "Not Matched between Transformation Type `" + transType + "` and the Instruction File type. : " + tempFileName; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } if (uploadedFilePath.toLowerCase().endsWith(".map")) { updateMapping(uploadedMapBak, path + File.separator + scenarioName); fileList.add(uploadedMapBak); fileList.add(uploadedFilePath); } else //xslt and xq { item.write(new File(uploadedFilePath)); fileList.add(uploadedFilePath); } } //else if (fieldName.equals("sourceXsdName")) else { String sourceORtarget = null; if (fieldName.startsWith("sourceXsdName")) sourceORtarget = SOURCE_DIRECTORY_TAG; else if (fieldName.startsWith("targetXsdName")) sourceORtarget = TARGET_DIRECTORY_TAG; if (sourceORtarget != null) { if (fileName.toLowerCase().endsWith(".xsd")) { if ((transType.equals("xq")) || (transType.equals("xsl"))) { String errMsg = "Transformation Type -" + transType + "- doesn't need any schema file."; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } uploadedFilePath = path + File.separator + scenarioName + File.separator + sourceORtarget + File.separator + fileName; //File file = new File(uploadedFilePath); //if ((file.exists())&&(file.isFile())) //{ // //} //else //{ System.out.println("AddNewScenario.doPost().." + sourceORtarget + " schema file:" + uploadedFilePath); item.write(new File(uploadedFilePath)); fileList.add(uploadedFilePath); String bakupFileName = uploadedFilePath + ".bak"; boolean ok = true; String er = ""; try { ok = replaceXSDFile(uploadedFilePath, bakupFileName, sourceORtarget, null); } catch (Exception ee) { er = ee.getMessage(); ok = false; } if (ok) { fileList.add(bakupFileName); } else { String errMsg = "Faild to upload this " + sourceORtarget + " schema file - " + fileName + ": " + er; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } //} } else if ((fileName.toLowerCase().endsWith(".zip")) || (fileName.toLowerCase().endsWith(".jar"))) { if ((transType.equals("xq")) || (transType.equals("xsl"))) { String errMsg = "Transformation Type `" + transType + "` doesn`t need any zip file."; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } uploadedFilePath = path + File.separator + scenarioName + File.separator + sourceORtarget + File.separator + fileName;//sourceORtarget+File.separator+fileName; //File file = new File(uploadedFilePath); //if ((file.exists())&&(file.isFile())) //{ // //} //else //{ System.out.println("AddNewScenario.doPost().." + sourceORtarget + " schema file:" + uploadedFilePath); item.write(new File(uploadedFilePath)); fileList.add(uploadedFilePath); if (sourceORtarget.equals(SOURCE_DIRECTORY_TAG)) { if (pathSourceZip != null) { String errMsg = "Only one zip file allowed - " + sourceORtarget + " :" + fileName; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } else pathSourceZip = uploadedFilePath; } else { if (pathTargetZip != null) { String errMsg = "Only one zip file allowed - " + sourceORtarget + " :" + fileName; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect( "errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } else pathTargetZip = uploadedFilePath; } //} } //else //{ // //} } } } } //boolean sourceZipCheckPass = false; //boolean targetZipCheckPass = false; if ((pathSourceZip != null) || (sourceOriginalXSDPath != null)) { try { extractXSDFileFromZip(pathSourceZip, sourceOriginalXSDPath, SOURCE_DIRECTORY_TAG); sourceOriginalXSDPath = null; } catch (Exception ee) { String errMsg = "Incomplete Source ZIP - " + pathSourceZip + " - file. : " + ee.getMessage(); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } //sourceZipCheckPass = true; } if ((pathTargetZip != null) || (targetOriginalXSDPath != null)) { try { extractXSDFileFromZip(pathTargetZip, targetOriginalXSDPath, TARGET_DIRECTORY_TAG); targetOriginalXSDPath = null; } catch (Exception ee) { String errMsg = "Incomplete Target ZIP - " + pathTargetZip + " - file. : " + ee.getMessage(); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } //targetZipCheckPass = true; } List<String> notFoundfiles = new ArrayList<String>(); for (String pathXSD : includedXSDList) { String xsdPath = path + File.separator + scenarioName + File.separator + pathXSD; File ff = new File(xsdPath); if ((!ff.exists()) || (!ff.isFile())) { //if ((sourceZipCheckPass)&&(pathXSD.startsWith(SOURCE_DIRECTORY_TAG + File.separator))) {} //else if ((targetZipCheckPass)&&(pathXSD.startsWith(TARGET_DIRECTORY_TAG + File.separator))) {} //else notFoundfiles.add(pathXSD); } } if ((notFoundfiles.size() > 0) || (!instructionFileFound)) { String errMsg = "Incomplete XSD files. Following " + notFoundfiles.size() + " required files are not uploaded. - "; if (notFoundfiles.size() == 1) errMsg = "Incomplete XSD files. Following one required file is not uploaded. - "; if (!instructionFileFound) errMsg = "No Instruction File is uploaded."; else for (String c : notFoundfiles) errMsg = errMsg + "<br>" + c; System.out.println("AddNewScenario.doPost()...ERROR:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } if ((transType.toLowerCase().equals("map")) && (mappingFileName != null)) { try { MappingFactory.loadMapping(new File(mappingFileName)); } catch (Exception ee) { String errMsg = ee.getMessage(); System.out.println("AddNewScenario.doPost()...ERROR on Load mapping file:" + errMsg); req.setAttribute("rtnMessage", errMsg); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(errMsg, "UTF-8")); return; } } ScenarioUtil.addNewScenarioRegistration(scenarioName, transType); res.sendRedirect("successmsg.do"); } catch (NullPointerException ne) { System.out.println("NullPointerException in doPost: " + ne); ne.printStackTrace(); req.setAttribute("rtnMessage", ne.getMessage()); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(ne.getMessage(), "UTF-8")); } catch (Exception e) { System.out.println("Error in doPost: " + e); e.printStackTrace(); req.setAttribute("rtnMessage", e.getMessage()); deleteDirAndFilesOnError(fileList); res.sendRedirect("errormsg.do" + "?message=" + URLEncoder.encode(e.getMessage(), "UTF-8")); } }
From source file:sharedcode.turboeditor.activity.MainActivity.java
public void onEvent(EventBusEvents.SavedAFile event) { sFilePath = event.getPath();/*from w ww. j a v a 2 s .c o m*/ fileExtension = FilenameUtils.getExtension(sFilePath).toLowerCase(); mEditor.clearHistory(); mEditor.fileSaved(); invalidateOptionsMenu(); try { closeKeyBoard(); } catch (NullPointerException e) { e.printStackTrace(); } refreshList(event.getPath(), true, false); arrayAdapter.selectView(event.getPath()); displayInterstitial(); }
From source file:sharedcode.turboeditor.activity.MainActivity.java
/** * Setup the navigation drawer/*ww w . j a va 2 s.c om*/ */ private void setupNavigationDrawer() { mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout); /* Action Bar final ActionBar ab = toolbar; ab.setDisplayHomeAsUpEnabled(true); ab.setHomeButtonEnabled(true);*/ /* Navigation drawer */ mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.nome_app_turbo_editor, R.string.nome_app_turbo_editor) { @Override public void onDrawerOpened(View drawerView) { supportInvalidateOptionsMenu(); try { closeKeyBoard(); } catch (NullPointerException e) { e.printStackTrace(); } } @Override public void onDrawerClosed(View view) { supportInvalidateOptionsMenu(); } }; /* link the mDrawerToggle to the Drawer Layout */ mDrawerLayout.setDrawerListener(mDrawerToggle); //mDrawerLayout.setFocusableInTouchMode(false); ListView listView = (ListView) findViewById(android.R.id.list); listView.setEmptyView(findViewById(android.R.id.empty)); files = new LinkedList<>(); arrayAdapter = new AdapterDrawer(this, files, this); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(this); }
From source file:ilearn.orb.controller.AnalysisController.java
@RequestMapping(value = "/analysis") public ModelAndView textAnalysis(Locale locale, ModelMap modelMap, HttpServletRequest request, HttpSession session) {/*from w ww.j a v a 2 s. c om*/ try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } ModelAndView model = new ModelAndView(); model.setViewName("analysis"); 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"); String profileId = request.getParameter("selectedId"); if (text != null) { text = new String(text.getBytes("8859_1"), "UTF-8"); } else text = ""; modelMap.put("profileId", profileId); modelMap.put("text", text); String json; if (Integer.parseInt(profileId) > 0) json = TextServices.getAnalysisJson(Integer.parseInt(profileId), session.getAttribute("auth").toString(), text); else json = TextServices .getAnalysisJson(HardcodedUsers.defaultProfileLanguage(Integer.parseInt(profileId)), text); AnalysisResults analysisResults = null; analysisResults = (new Gson()).fromJson(json, AnalysisResults.class); modelMap.put("analysisResults", analysisResults); UserProfile pr = retrieveProfile(session, Integer.parseInt(profileId)); modelMap.put("selectedProfile", pr); int maxWordsMatched = 0; for (int i = 0; i < pr.getUserProblems().getNumerOfRows(); i++) { for (int j = 0; j < pr.getUserProblems().getRowLength(i); j++) { if (analysisResults.getUserCounters().getValue(i, j) > maxWordsMatched) maxWordsMatched = analysisResults.getUserCounters().getValue(i, j); } } modelMap.put("maxWordsMatched", maxWordsMatched); } catch (NumberFormatException e) { //e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return model; }
From source file:jdbc.pool.JDBCPoolTestCase.java
public void testEmptyAllPools() { System.out.println("testEmptyAllPools Start"); CConnectionPoolManager manager = null; try {/*from w w w. j a va 2 s . c o m*/ manager = create(); Connection con = manager.getConnection("ORACLE"); // MYSQL is load // on startup. con.close(); manager.emptyAllPools(false); try { manager.getPoolStatistics("ORACLE"); fail("Should have thrown NullPointerException."); } catch (NullPointerException e) { assertTrue("Caught NullPointerException", true); } try { manager.getPoolStatistics("MYSQL"); fail(); } catch (NullPointerException e) { assertTrue("Caught NullPointerException", true); } } 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"); } finally { manager.destroy(true); testGetInstanceNull(); } System.out.println("testEmptyAllPools end."); }
From source file:jdbc.pool.JDBCPoolTestCase.java
public void testForceShutdown() { System.out.println("testForceShutdown Start"); CConnectionPoolManager manager = null; try {/*from w w w .j av a 2 s .c om*/ manager = create(); Connection con = manager.getConnection("ORACLE"); // MYSQL is load // on startup. manager.emptyAllPools(true); if (con instanceof ConnectionWrapper) { ConnectionWrapper realCon = (ConnectionWrapper) con; assertTrue("Is realConnection closed?", realCon.realConnection().isClosed()); } assertTrue("Passed. Even if the pool was in use it did not throw any exception.", true); try { manager.getPoolStatistics("ORACLE"); fail("Should have thrown NullPointerException."); } catch (NullPointerException e) { assertTrue("Caught NullPointerException", true); } try { manager.getPoolStatistics("ORACLE"); fail(); } catch (NullPointerException e) { assertTrue("Caught NullPointerException", true); } } 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"); } finally { manager.destroy(true); testGetInstanceNull(); } System.out.println("testForceShutdown end."); }