List of usage examples for java.lang NullPointerException getMessage
public String getMessage()
From source file:org.geoserver.gwc.GWCTest.java
@Test public void testModifyGridsetPreconditions() throws Exception { GridSet oldGridset = gridSetBroker.get("EPSG:4326"); try {/*from w w w . j av a 2 s . c o m*/ mediator.modifyGridSet(null, oldGridset); fail(); } catch (NullPointerException e) { assertTrue(true); } try { mediator.modifyGridSet("oldname", null); fail(); } catch (NullPointerException e) { assertTrue(true); } try { mediator.modifyGridSet("wrongOldName", oldGridset); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("does not exist")); } }
From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java
@TargetApi(18) private boolean supportsBeacons() { boolean available = false; try {/*from ww w. ja v a2s. com*/ available = BeaconManager.getInstanceForApplication(mService).checkAvailability(); } catch (NullPointerException ex) { L.i("BLE not available", ex); } catch (BleNotAvailableException ex) { L.d(ex.getMessage()); } if (!available) { L.d("Bluetooth is not enabled"); } return available; }
From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java
@TargetApi(18) private void bindBeaconManager() { if (CloudConstants.DEBUG_LOGGING) { LogManager.setLogger(Loggers.verboseLogger()); LogManager.setVerboseLoggingEnabled(true); } else {//from w ww . j a v a2 s . c o m LogManager.setLogger(Loggers.empty()); LogManager.setVerboseLoggingEnabled(false); } if (!mService.isPermitted(Manifest.permission.ACCESS_COARSE_LOCATION)) { L.w("ACCESS_COARSE_LOCATION is not permitted!"); return; } mBeaconManager = BeaconManager.getInstanceForApplication(mService); if (!mBeaconManager.isAnyConsumerBound()) { mBeaconManager.getBeaconParsers() .add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25")); } try { if (!mBeaconManager.checkAvailability()) { L.d("Bluetooth is not enabled"); } mBeaconManager.bind(mService); mBeaconManager.setBackgroundMode(!mService.getScreenIsOn()); } catch (NullPointerException ex) { L.i("BLE not available", ex); } catch (BleNotAvailableException ex) { L.d(ex.getMessage()); } }
From source file:org.apache.torque.DataTest.java
/** * Test the behaviour if a connection is supplied to access the database, * but it is null. All methods on the user level should be fail * because these methods will be only needed if a method should be executed * in a transaction context. If one assumes that a transaction is open * (connection is not null), but it is not (connection == null), * it is a bad idea to silently start one as this behaviour is very * difficult to tell from the correct one. A clean failure is much easier * to test for./* w w w . j a v a2 s . c om*/ */ public void testNullConnection() throws Exception { try { Criteria criteria = new Criteria(); AuthorPeer.doSelect(criteria, new IntegerMapper(), null); fail("NullPointerException expected"); } catch (NullPointerException e) { //expected } try { Criteria criteria = new Criteria(); criteria.where(BookPeer.BOOK_ID, (Long) null, Criteria.NOT_EQUAL); BookPeer.doDelete(criteria, (Connection) null); fail("NullPointerException expected"); } catch (NullPointerException e) { //expected } try { Author author = new Author(); author.setName("name"); author.save((Connection) null); fail("TorqueException expected"); } catch (TorqueException e) { //expected assertEquals("connection is null", e.getMessage()); } }
From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java
/** * /*from w w w. ja v a 2 s .c o m*/ * @param username : requested user name * @param calendarId : calendar id from system * @param type : calendar type * @return : Rss feeds * @throws Exception */ @SuppressWarnings("unchecked") @GET @RolesAllowed("users") @Path("/feed/{username}/{feedname}/{filename}/") public Response feed(@PathParam("username") String username, @PathParam("feedname") String feedname, @PathParam("filename") String filename) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); try { if (!isAuthorized(username)) return Response.status(HTTPStatus.LOCKED).entity("Unauthorized: Access is denied") .cacheControl(cacheControl).build(); CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(CalendarService.class); // TODO getFeed(String feedname) FeedData feed = null; for (FeedData feedData : calService.getFeeds(username)) { if (feedData.getTitle().equals(feedname)) { feed = feedData; break; } } SyndFeedInput input = new SyndFeedInput(); SyndFeed syndFeed = input.build(new XmlReader(new ByteArrayInputStream(feed.getContent()))); List<SyndEntry> entries = new ArrayList<SyndEntry>(syndFeed.getEntries()); List<CalendarEvent> events = new ArrayList<CalendarEvent>(); for (SyndEntry entry : entries) { String calendarId = entry.getLink().substring(entry.getLink().lastIndexOf("/") + 1); List<String> calendarIds = new ArrayList<String>(); calendarIds.add(calendarId); Calendar calendar = calService.getUserCalendar(username, calendarId); if (calendar != null) { events.addAll(calService.getUserEventByCalendar(username, calendarIds)); } else { try { calendar = calService.getSharedCalendars(username, false).getCalendarById(calendarId); } catch (NullPointerException e) { calendar = null; } if (calendar != null) { events.addAll(calService.getSharedEventByCalendars(username, calendarIds)); } else { calendar = calService.getGroupCalendar(calendarId); if (calendar != null) { EventQuery eventQuery = new EventQuery(); eventQuery.setCalendarId(calendarIds.toArray(new String[] {})); events.addAll(calService.getPublicEvents(eventQuery)); } } } } if (events.size() == 0) { return Response.status(HTTPStatus.NOT_FOUND).entity("Feed " + feedname + "is removed") .cacheControl(cacheControl).build(); } return Response.ok(makeFeed(username, events, feed), MediaType.APPLICATION_XML) .cacheControl(cacheControl).build(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug(e.getMessage()); return Response.status(HTTPStatus.INTERNAL_ERROR).entity(e).cacheControl(cacheControl).build(); } }
From source file:org.goobi.presentation.contentservlet.controller.GetMetsPdfAction.java
/************************************************************************************ * exectute mets handling and generation of pdf file and send pdf back to output stream of the servlet, after setting correct mime type * /*from w w w .j a v a 2 s. com*/ * @param request {@link HttpServletRequest} of ServletRequest * @param response {@link HttpServletResponse} for writing to response output stream * @throws IOException * @throws ServletException * @throws ContentLibException * @throws URISyntaxException * @throws CacheException ************************************************************************************/ @Override public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ContentLibException, URISyntaxException, CacheException { /* first of all validation */ validateParameters(request); /* * -------------------------------- get central configuration and retrieve source image from url -------------------------------- */ ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(request, watermarkfile); } OutputStream myOutStream = response.getOutputStream(); ContentCache cc = ContentServer.getPdfCache(); String myUniqueID = getContentCacheIdForRequest(request, config); setTargetNameAndMimeType(request, response, config); try { /* * -------------------------------- ask ContentCache, if object already exists -------------------------------- */ PDFManager pdfmanager = null; try { boolean ignoreCache = false; /* check if cache should be ignored */ if (request.getParameter("ignoreCache") != null) { String ignore = request.getParameter("ignoreCache").trim(); ignoreCache = Boolean.parseBoolean(ignore); } if (cc == null || !config.getPdfCacheUse()) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } /* if cache should not be ignored and cache contains file, write it back to stream */ if (!ignoreCache && cc.cacheContains(myUniqueID, "pdf")) { LOGGER.debug("get file from cache: " + myUniqueID); cc.writeToStream(response.getOutputStream(), myUniqueID, "pdf"); return; } else if (ignoreCache == false) { LOGGER.debug("file not found in cache: " + myUniqueID); } /* * -------------------------------- if Cache is not used, parse mets file name and add it to repository path * -------------------------------- */ String metsFile = request.getParameter("metsFile"); if (!metsFile.endsWith(".xml")) { metsFile += ".xml"; } URL fullMetsPath = new URL(config.getRepositoryPathMets() + metsFile); LOGGER.debug("mets file to parse: " + fullMetsPath); /* * -------------------------------- open METS file -------------------------------- */ METSParser metsparser = new METSParser(fullMetsPath, true); SimplePDFMetadataExtractor spme = new SimplePDFMetadataExtractor(); spme.activateDFGConfiguration(); // set the Metadata extractor and the Bookmark metadata extractor metsparser.setMetadataextractor(spme); metsparser.setStructureMetadataExtractor(new SimpleStructureMetadataExtractor()); /* * -------------------------------- check if filegroup is defined in request parameter, else take it from config file * -------------------------------- */ String strMetsFileGroup = request.getParameter("metsFileGroup"); if (strMetsFileGroup == null) { strMetsFileGroup = config.getDefaultMetsFileGroup(); } metsparser.setFilegroupsuseattributevalue(strMetsFileGroup); LOGGER.debug("Using METS file group: " + strMetsFileGroup); /* * -------------------------------- check divID as parameter, else use upper most divID -------------------------------- */ String divID = request.getParameter("divID"); DivType pdfdiv = null; if (StringUtils.isNotBlank(divID)) { pdfdiv = metsparser.getDIVbyID(divID); // check if the METS file is a monograph, volume or multivolume file } else { DivType uplogdiv = metsparser.getUppermostLogicalDiv(); if (uplogdiv == null) { throw new ContentLibPdfException("Can't create PDF; div seems to be an anchor."); } // check, if we have <mptr> as children List<Mptr> mptrs = uplogdiv.getMptrList(); if ((mptrs == null) || (mptrs.size() == 0)) { // no mptr - must be a monograph // in this case the uppermost logical id is the one we are looking for pdfdiv = uplogdiv; } else { // check, if we have a physical structmap DivType physDiv = metsparser.getUppermostPhysicalDiv(); if (physDiv == null) { // it is a multivolume or a periodical or anything like this // in this case the uppermost logical div is the one for which we create the PDF pdfdiv = uplogdiv; } else { // it is the first child div; this represents the volume List<DivType> children = uplogdiv.getDivList(); if ((children == null) || (children.size() == 0)) { throw new ContentLibPdfException("Can't create PDF; can't find a div"); } pdfdiv = children.get(0); // the first child } } } spme.calculateMetadata(pdfdiv, metsparser); metsparser.getAllFilesForRelatedDivs(pdfdiv.getID()); // get page names /* * -------------------------------- get list of files and pagenames -------------------------------- */ Map<Integer, UrlImage> myPages = metsparser.getImageMap(); // HashMap<Integer, URL> myURLs = metsparser.getPageUrls(); Map<Integer, String> myNames = metsparser.getPageNames(); List<? extends Structure> pDFBookmarks = metsparser.getStructureList(); // PDFManager pdfmanager = new PDFManager(myURLs); pdfmanager = new PDFManager(myPages, true); setPdfManagerDefaults(request, config, pdfmanager); /* * -------------------------------- set pdf meta data -------------------------------- */ if (spme.getPdftitle() != null) { String title = spme.getPdftitle().trim(); pdfmanager.setTitle(title); } if (spme.getPdfcreator() != null) { String creator = spme.getPdfcreator().trim(); pdfmanager.setCreator(creator); pdfmanager.setAuthor(creator); } if (spme.getPdfkeywords() != null) { pdfmanager.setSubject(spme.getPdfkeywords()); } /* * -------------------------------- if configured create PDF title page - either read its path from config file and fill it with mets * content - or if given as url parameter use it directly without any change -------------------------------- */ if (config.getPdfTitlePageUse()) { PDFTitlePage pdftp = new PDFTitlePage(); String pdfconfigurl = request.getParameter("pdftitlepage"); if (StringUtils.isNotBlank(pdfconfigurl)) { pdftp.readConfiguration(new URI(pdfconfigurl)); } else { pdftp.readConfiguration(config.getPdfTitlePageConfigFile()); if (spme.getPdfTitlepageLine1() != null) { PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine1()); ptl.setLinetype(2); ptl.setFontsize(14); pdftp.addPDFTitlePageLine(ptl); } if (spme.getPdfTitlepageLine2() != null) { PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine2()); ptl.setLinetype(2); ptl.setFontsize(10); pdftp.addPDFTitlePageLine(ptl); } if (spme.getPdfTitlepageLine3() != null) { PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine3()); ptl.setLinetype(2); ptl.setFontsize(10); pdftp.addPDFTitlePageLine(ptl); } if (spme.getPdfTitlepageLine4() != null) { PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine4()); ptl.setLinetype(2); ptl.setFontsize(10); pdftp.addPDFTitlePageLine(ptl); } } pdfmanager.setPdftitlepage(pdftp); } /* * -------------------------------- set page names and bookmarks -------------------------------- */ if ((myNames != null) && (myNames.size() > 0)) { pdfmanager.setImageNames(myNames); } if ((pDFBookmarks != null) && (pDFBookmarks.size() > 0)) { pdfmanager.setStructureList(pDFBookmarks); } /* * -------------------------------- write pdf to response stream (and cache) -------------------------------- */ /* remove file from cache, if cache should be used and file present */ if (cc != null) { cc.delete(myUniqueID, "pdf"); } /* if cache size is exceeded write it to response stream only */ if (cc != null && !cc.isCacheSizeExceeded()) { LOGGER.info("write file to cache and servlet response: " + cc.getFileForId(myUniqueID, "pdf")); myOutStream = new CacheOutputStream(cc.getFileForId(myUniqueID, "pdf"), response.getOutputStream()); } else if (cc == null) { LOGGER.info("file will not be written to cache, cache is deactivated in configuration"); } else if (cc.isCacheSizeExceeded()) { LOGGER.info( "file will not be written to cache, maximum cache size exceeded defined configuration"); } } catch (NullPointerException e) { throw new NullPointerException("Nullpointer occured before pdf-generation"); } /* write to stream */ if (pdfmanager != null) { pdfmanager.createPDF(myOutStream, getPageSize(request), myWatermark); } } catch (Exception e) { LOGGER.error("error during pdf generation (" + e.getClass().getName() + ")", e); Document pdfdoc = new Document(); PdfWriter writer; try { writer = PdfWriter.getInstance(pdfdoc, myOutStream); } catch (DocumentException e1) { throw new ContentLibException("wrapped DocumentException", e1); } pdfdoc.open(); /*--------------------------------- * Generate Watermark *---------------------------------*/ String errorString = e.getClass().getName() + ": " + e.getMessage(); String jpgfile = new File(Util.getBaseFolderAsFile(), "errorfile.jpg").getAbsolutePath(); LOGGER.debug("errorfile to embedd: " + jpgfile); FileInputStream inputFileStream = new FileInputStream(jpgfile); RenderedImage ri = ServletWatermark.generateErrorWatermark(inputFileStream, errorString) .getRenderedImage(); /* * -------------------------------- prepare target and read created image -------------------------------- */ BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri); Image pdfImage; try { pdfImage = Image.getInstance(buffImage, null, false); pdfdoc.add(pdfImage); } catch (BadElementException e1) { LOGGER.error("error while adding pdfImage", e); throw new ContentLibException("wrapped BadElementException", e1); } catch (DocumentException e2) { LOGGER.error("error while adding pdfImage", e); throw new ContentLibException("wrapped DocumentException", e2); } finally { /* * -------------------------------- close all -------------------------------- */ try { if (inputFileStream != null) { inputFileStream.close(); } if (pdfdoc != null) { pdfdoc.close(); } if (writer != null) { writer.close(); } } catch (ExceptionConverter e2) { LOGGER.warn("Caught ExceptionConverter object"); } finally { /* on errors remove incomplete file from cache */ try { if (myOutStream != null) { myOutStream.flush(); myOutStream.close(); } } catch (Exception e2) { LOGGER.debug("Caught unknown Exception"); } if (cc != null && cc.cacheContains(myUniqueID, "pdf")) { cc.delete(myUniqueID, "pdf"); } } } } finally { if (myOutStream != null) { myOutStream.flush(); myOutStream.close(); } } }
From source file:com.wso2telco.gsma.handlers.authenticationstephandler.MIFEAuthenticationStepHandler.java
@SuppressWarnings("unchecked") @Override/*from w ww . ja va 2 s. c om*/ protected void doAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatorConfig authenticatorConfig) throws FrameworkException { log.info("Do authentication..."); SequenceConfig sequenceConfig = context.getSequenceConfig(); int currentStep = context.getCurrentStep(); StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep); AuthenticationRequest authRequest = context.getAuthenticationRequest(); Map<String, String[]> paramMap = authRequest.getRequestQueryParams(); String scope; String redirectUri; String state = null; String responseType; String client_id = paramMap.get(Params.CLIENT_ID.toString())[0]; ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator(); try { context.setAuthenticatorProperties(FrameworkUtils .getAuthenticatorPropertyMapFromIdP(context.getExternalIdP(), authenticator.getName())); AuthenticatorFlowStatus status = authenticator.process(request, response, context); //The following if block is a part of implementing the functionality of SMSAuthenticator //getting hit ONLY when the link to get a text message is clicked in the USSD waiting page. //This ensures that after USSDAuthenticator is executed, SMS authenticator doesn't get hit. if ("true".equals(context.getProperty(Constants.TERMINATE_BY_REMOVE_FOLLOWING_STEPS))) { removeAllFollowingSteps(context, currentStep); context.setProperty("removeFollowingSteps", null); } request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status); //state validation if (!paramMap.containsKey(Params.STATE.toString())) { redirectUri = paramMap.get(Params.REDIRECT_URI.toString())[0]; String invalidRedirectUrl = redirectUri + "?error=invalid_request&error_description=state_required"; if (log.isDebugEnabled()) { log.debug("state not found. client_id : " + client_id); } try { response.sendRedirect(invalidRedirectUrl); } catch (IOException ex) { // Logger.getLogger(MIFEAuthenticationStepHandler.class.getName()).log(Level.SEVERE, null, ex); log.error("Failed to access Redirect URL: " + invalidRedirectUrl, ex); } } else { state = paramMap.get(Params.STATE.toString())[0]; redirectUri = paramMap.get(Params.REDIRECT_URI.toString())[0]; } //scope validation redirectUri = validateScope(response, paramMap, redirectUri, state, client_id); //responseType validation validateResponseType(response, paramMap, redirectUri, client_id); //nonce validation validateNonce(response, paramMap, redirectUri, client_id); if (log.isDebugEnabled()) { log.debug(authenticator.getName() + " returned: " + status.toString()); } if (status == AuthenticatorFlowStatus.INCOMPLETE) { if (log.isDebugEnabled()) { log.debug(authenticator.getName() + " is redirecting"); } return; } // This is only a routing authenticator if (authenticator instanceof LOACompositeAuthenticator) { removeFailedStep(context, currentStep); } else { try { if (Boolean.parseBoolean(authenticatorConfig.getParameterMap().get("isLastAuthenticator"))) { removeAllFollowingSteps(context, currentStep); } // set authenticator name in the context // This gets used in ID token later Object amrValue = context.getProperty(Params.AMR.toString()); List<String> amr; if (null != amrValue && amrValue instanceof ArrayList<?>) { amr = (ArrayList<String>) amrValue; } else { amr = new ArrayList(); } // Add authenticator AMR value if current authenticator is an instance of // BaseApplicationAuthenticator if (authenticator instanceof BaseApplicationAuthenticator) { String amrValueFromAuthenticator = ((BaseApplicationAuthenticator) authenticator) .getAmrValue((int) context.getParameter(Constants.ACR)); if (amrValueFromAuthenticator != null) { amr.add(amrValueFromAuthenticator); } } context.setProperty(Params.AMR.toString(), amr); } catch (NullPointerException e) { // Possible exception during dashboard login // Should continue even if NPE is thrown } setAuthenticationAttributes(context, stepConfig, authenticatorConfig); } } catch (AuthenticationFailedException e) { boolean followingStepsRemoved = false; //The following if block is a part of implementing the functionality of SMSAuthenticator //getting hit ONLY when the link to get a text message is clicked in the USSD waiting page. //This ensures when USSDAuthenticator is failed, SMS authenticator doesn't get hit. if ("true".equals(context.getProperty(Constants.TERMINATE_BY_REMOVE_FOLLOWING_STEPS))) { removeAllFollowingSteps(context, currentStep); context.setProperty(Constants.TERMINATE_BY_REMOVE_FOLLOWING_STEPS, null); followingStepsRemoved = true; } if (e instanceof InvalidCredentialsException) { log.error("A login attempt was failed due to invalid credentials"); } else { log.error(e.getMessage(), e); } // add failed authenticators Object amrValue = context.getProperty("failedamr"); List<String> amr; if (null != amrValue && amrValue instanceof ArrayList<?>) { amr = (ArrayList<String>) amrValue; } else { amr = new ArrayList<String>(); } amr.add(authenticator.getName()); context.setProperty("failedamr", amr); // Remove failed step from step map removeFailedStep(context, currentStep); try { String onFailProperty = authenticatorConfig.getParameterMap().get("onFail"); if (!"".equals(onFailProperty) && !onFailProperty.equals("continue")) { // Should fail the whole LOA and continue to next if defined String fallBacklevel = authenticatorConfig.getParameterMap().get("fallBack"); if (onFailProperty.equals("fallback") && StringUtils.isNotBlank(fallBacklevel) && !followingStepsRemoved) { removeFollowingStepsOfCurrentLOA(context, authenticatorConfig.getParameterMap().get("currentLOA"), currentStep); } else { context.setRequestAuthenticated(false); context.getSequenceConfig().setCompleted(true); } } } catch (NullPointerException e1) { // Possible exception during dashboard login removeAllFollowingSteps(context, currentStep); context.setRequestAuthenticated(false); context.getSequenceConfig().setCompleted(true); } } catch (LogoutFailedException e) { throw new FrameworkException(e.getMessage(), e); } stepConfig.setCompleted(true); }
From source file:it.cnr.icar.eric.client.ui.thin.RegistryObjectBean.java
/** * Change the current ExternalURI for ExternalLink * @param none//from w w w . j av a 2 s . co m * @return none */ public void changeExternalURI() { RegistryObject ro = this.registryObject; try { if (externalURI != null && externalURI.trim().length() >= 0) { ((ExternalLinkImpl) ro).setExternalURI(externalURI); } else if (this.externalURI == null && ro instanceof ExternalLinkImpl) { ((ExternalLinkImpl) ro).setExternalURI(((ExternalLinkImpl) ro).getExternalURI()); } } catch (NullPointerException nep) { setRegistryObjectErrorMessage(WebUIResourceBundle.getInstance().getString("nullExternalURIError")); String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError"); log.error(errMsg + " " + nep.getMessage()); } catch (java.lang.RuntimeException re) { if (re.getCause() instanceof IllegalArgumentException) { setRegistryObjectErrorMessage( WebUIResourceBundle.getInstance().getString("illegalExternalURIError")); } String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError"); log.error(errMsg + " " + re.getMessage()); } catch (Exception ex) { setRegistryObjectErrorMessage("ExternalURI " + ex.getMessage()); String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError"); log.error(errMsg + " " + ex.getMessage()); } }
From source file:gov.nih.nci.cbiit.cmts.ws.servlet.AddNewScenario.java
/** ********************************************************** * doPost()/*from www.j av a 2 s.c o m*/ ************************************************************ */ 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:jp.terasoluna.fw.web.struts.form.DynaValidatorActionFormExTest.java
/** * testSetStringintObject02()//w w w .ja v a 2 s . c o m * <br><br> * * (?n) * <br> * _?FG * <br><br> * l?F(?) name:<br> * (?) index:0<br> * (?) value:"hello"<br> * * <br> * l?F(?) O:NullPointerException?F<br> * ?bZ?[W?F"No indexed value for '[0]'"<br> * (?) namewtB?[h:?|<br> * * <br> * name??ANullPointerExceptionX??[mF?B * <br> * * @throws Exception ?\bh?O */ public void testSetStringintObject02() throws Exception { //eXg?s try { this.formEx.set("", 0, "hello"); fail(); } catch (NullPointerException e) { //eXgmF assertEquals("No indexed value for '[0]'", e.getMessage()); } }