List of usage examples for java.lang NumberFormatException printStackTrace
public void printStackTrace()
From source file:com.lgallardo.qbittorrentclient.RefreshListener.java
protected void getSettings() { // Preferences stuff sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); builderPrefs = new StringBuilder(); builderPrefs.append("\n" + sharedPrefs.getString("language", "NULL")); // Get values from preferences currentServer = sharedPrefs.getString("currentServer", "1"); hostname = sharedPrefs.getString("hostname", ""); subfolder = sharedPrefs.getString("subfolder", ""); protocol = sharedPrefs.getString("protocol", "NULL"); // If user leave the field empty, set 8080 port try {//from w ww .ja v a2 s. c om port = Integer.parseInt(sharedPrefs.getString("port", "8080")); } catch (NumberFormatException e) { port = 8080; } username = sharedPrefs.getString("username", "NULL"); password = sharedPrefs.getString("password", "NULL"); https = sharedPrefs.getBoolean("https", false); // Check https if (https) { protocol = "https"; } else { protocol = "http"; } // Get refresh info auto_refresh = sharedPrefs.getBoolean("auto_refresh", true); try { refresh_period = Integer.parseInt(sharedPrefs.getString("refresh_period", "120000")); } catch (NumberFormatException e) { refresh_period = 120000; } // Get connection and data timeouts try { connection_timeout = Integer.parseInt(sharedPrefs.getString("connection_timeout", "10")); // New default value to make it work with qBittorrent 3.2.x if (connection_timeout < 10) { connection_timeout = 10; } } catch (NumberFormatException e) { connection_timeout = 10; } try { data_timeout = Integer.parseInt(sharedPrefs.getString("data_timeout", "20")); // New default value to make it work with qBittorrent 3.2.x if (data_timeout < 20) { data_timeout = 20; } } catch (NumberFormatException e) { data_timeout = 20; } sortby_value = sharedPrefs.getInt("sortby_value", 1); reverse_order = sharedPrefs.getBoolean("reverse_order", false); dark_ui = sharedPrefs.getBoolean("dark_ui", false); qb_version = sharedPrefs.getString("qb_version", "3.2.x"); MainActivity.cookie = sharedPrefs.getString("qbCookie", null); // Get last state lastState = sharedPrefs.getString("lastState", "all"); // Get last label // lastLabel = sharedPrefs.getString("lastLabel", "all"); lastLabel = sharedPrefs.getString("lastLabel", "all"); currentLabel = lastLabel; // Notification check enable_notifications = sharedPrefs.getBoolean("enable_notifications", false); try { notification_period = Long.parseLong(sharedPrefs.getString("notification_period", "120000L")); } catch (NumberFormatException e) { notification_period = 120000L; } header = sharedPrefs.getBoolean("header", true); // Get package info PackageInfo pInfo = null; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } // Get package name packageName = pInfo.packageName; packageVersion = pInfo.versionName; // Get AlternativeSpeedLimitsEnabled value alternative_speeds = sharedPrefs.getBoolean("alternativeSpeedLimitsEnabled", false); // Get local SSID properties ssid = sharedPrefs.getString("ssid", ""); local_hostname = sharedPrefs.getString("local_hostname", null); // If user leave the field empty, set 8080 port try { local_port = Integer.parseInt(sharedPrefs.getString("local_port", "-1")); } catch (NumberFormatException e) { local_port = -1; } // Set SSI and local hostname and port if (ssid != null && !ssid.equals("")) { // Get SSID if WiFi WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); String wifiSSID = wifiInfo.getSSID(); // Log.d("Debug", "WiFi SSID: " + wifiSSID); // Log.d("Debug", "SSID: " + ssid); if (wifiSSID.toUpperCase().equals("\"" + ssid.toUpperCase() + "\"") && wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { if (local_hostname != null && !local_hostname.equals("")) { hostname = local_hostname; } if (local_port != -1) { port = local_port; } // Log.d("Debug", "hostname: " + hostname); // Log.d("Debug", "port: " + port); // Log.d("Debug", "local_hostname: " + local_hostname); // Log.d("Debug", "local_port: " + local_port); } } // Get keystore for self-signed certificate keystore_path = sharedPrefs.getString("keystore_path" + currentServer, ""); keystore_password = sharedPrefs.getString("keystore_password" + currentServer, ""); }
From source file:org.eclipse.buckminster.jnlp.p2.Application.java
public Object start(IApplicationContext context) throws Exception { Object runArgs = context.getArguments().get(IApplicationContext.APPLICATION_ARGS); String errorCode = null;/* ww w .ja v a 2 s . co m*/ try { String configUrl = null; Long popupAfter = null; if (runArgs instanceof String[]) { String[] args = (String[]) runArgs; for (int idx = 0; idx < args.length; ++idx) { String arg = args[idx]; if ("-configURL".equals(arg)) { if (++idx < args.length) { configUrl = args[idx]; if (configUrl != null) { configUrl = configUrl.trim(); if (configUrl.length() == 0) configUrl = null; } } } else if ("-syncString".equals(arg)) { if (++idx < args.length) { m_syncString = args[idx]; if (m_syncString != null) { m_syncString = m_syncString.trim(); if (m_syncString.length() == 0) m_syncString = null; } } } else if ("-popupAfter".equals(arg)) { if (++idx < args.length) { try { popupAfter = Long.valueOf(args[idx]); } catch (NumberFormatException e) { // popupAfter remains null } } } } } // We need to create a display first thing since many mechanisms // depend on its presence. // Display.setAppName("Materializer"); Display display = Display.getDefault(); HelpLinkErrorDialog.setSyncString(m_syncString); if (!Platform.getInstanceLocation().lock()) { errorCode = MaterializationConstants.ERROR_CODE_ALREADY_RUNNING_EXCEPTION; throw BuckminsterException.fromMessage("Materializer is already running"); } BuckminsterPreferences.setLogLevelConsole(Logger.SILENT); BuckminsterPreferences.setLogLevelEclipseLogger(Logger.DEBUG); if (configUrl == null) { errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION; throw BuckminsterException .fromMessage("Missing required argument -configURL <URL to config properties>"); } Map<String, String> properties = new HashMap<String, String>(); InputStream propStream = null; try { URL propertiesURL = new URL(configUrl); propStream = new BufferedInputStream(propertiesURL.openStream()); Map<String, String> allProperties = new BMProperties(propStream); // Get rid of empty properties for (Map.Entry<String, String> entry : allProperties.entrySet()) { String value = entry.getValue(); if (!(value == null || value.trim().length() == 0)) properties.put(entry.getKey(), value); } } catch (IOException e) { errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION; throw BuckminsterException.fromMessage(e, "Can not read materialization information"); } finally { IOUtils.close(propStream); } m_errorURL = properties.get(MaterializationConstants.PROP_ERROR_URL); if (m_errorURL == null) m_errorURL = MaterializationConstants.ERROR_HELP_URL; m_supportEmail = properties.get(MaterializationConstants.PROP_SUPPORT_EMAIL); String errorMessage = properties.get(MaterializationConstants.PROP_ERROR_MESSAGE); if (errorMessage != null) { errorCode = MaterializationConstants.ERROR_CODE_404_EXCEPTION; throw BuckminsterException .fromMessage(new String(Base64.decodeBase64(errorMessage.getBytes()), "UTF-8")); //$NON-NLS-1$ } try { // Create the wizard dialog and resize it. // final InstallWizard installWizard = new InstallWizard(properties); m_errorURL = installWizard.getErrorURL(); AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~SWT.APPLICATION_MODAL); dialog.create(); // General exception handler Window.setExceptionHandler(new IExceptionHandler() { public void handleException(Throwable t) { if (t instanceof ThreadDeath) { // Don't catch ThreadDeath as this is a normal occurrence when // the thread dies throw (ThreadDeath) t; } IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t) .getStatus(); CorePlugin.logWarningsAndErrors(status); String localErrorCode; String message; boolean reportable; if (t instanceof JNLPException) { JNLPException e = (JNLPException) t; localErrorCode = e.getErrorCode(); message = e.getMessage(); reportable = e.isReportable(); } else { localErrorCode = ERROR_CODE_RUNTIME_EXCEPTION; message = "An unexpected error occurred.\n\nThis could be because of intermittent network problems."; reportable = true; } HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(), MaterializationConstants.ERROR_WINDOW_TITLE, message, status, localErrorCode, reportable, m_supportEmail, "Materialization Error"); } }); final Shell shell = dialog.getShell(); shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH), Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT)); // when the shell is not started "ON TOP", it starts blinking shell.addShellListener(new ShellAdapter() { private int m_cnt = 0; @Override public void shellActivated(ShellEvent e) { if (m_cnt == 0) { Display.getDefault().asyncExec(new Runnable() { public void run() { shell.forceActive(); } }); m_cnt++; } } }); try { if (popupAfter != null) { long popupDelay = popupAfter.longValue() - (new Date()).getTime(); if (popupDelay > 0) Thread.sleep(popupDelay); } synchronizeWithBootstrap(); long popupDelay = DEFAULT_POPUP_DELAY; String popupDelayString = properties.get(MaterializationConstants.PROP_POPUP_DELAY); if (popupDelayString != null) { try { popupDelay = new Long(popupDelayString).longValue(); } catch (Throwable e) { popupDelay = DEFAULT_POPUP_DELAY; } } // need to wait a while until applet finishes Thread.sleep(popupDelay); dialog.open(); return OK_EXIT_CODE; } catch (Throwable e) { errorCode = ERROR_CODE_RUNTIME_EXCEPTION; final String finalErrorCode = errorCode; final IStatus status = BuckminsterException.wrap(e).getStatus(); CorePlugin.logWarningsAndErrors(status); Display.getDefault().syncExec(new Runnable() { public void run() { HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE, "Materialization wizard failed", status, finalErrorCode, true, m_supportEmail, "Materialization Error"); } }); return ERROR_EXIT_CODE; } } finally { display.dispose(); } } catch (Throwable e) { e.printStackTrace(); if (errorCode == null) { errorCode = ERROR_CODE_RUNTIME_EXCEPTION; } final String finalErrorCode = errorCode; final IStatus status = BuckminsterException.wrap(e).getStatus(); CorePlugin.logWarningsAndErrors(status); Display.getDefault().syncExec(new Runnable() { public void run() { HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE, "Materialization cannot be started", status, finalErrorCode, true, m_supportEmail, "Materialization Error"); } }); return ERROR_EXIT_CODE; } }
From source file:org.eclipse.buckminster.jnlp.Application.java
public Object start(IApplicationContext context) throws Exception { Object runArgs = context.getArguments().get(IApplicationContext.APPLICATION_ARGS); String errorCode = null;/*from www . j av a 2 s . c om*/ try { String configUrl = null; Long popupAfter = null; if (runArgs instanceof String[]) { String[] args = (String[]) runArgs; for (int idx = 0; idx < args.length; ++idx) { String arg = args[idx]; if ("-configURL".equals(arg)) //$NON-NLS-1$ { if (++idx < args.length) { configUrl = args[idx]; if (configUrl != null) { configUrl = configUrl.trim(); if (configUrl.length() == 0) configUrl = null; } } } else if ("-syncString".equals(arg)) //$NON-NLS-1$ { if (++idx < args.length) { m_syncString = args[idx]; if (m_syncString != null) { m_syncString = m_syncString.trim(); if (m_syncString.length() == 0) m_syncString = null; } } } else if ("-popupAfter".equals(arg)) //$NON-NLS-1$ { if (++idx < args.length) { try { popupAfter = Long.valueOf(args[idx]); } catch (NumberFormatException e) { // popupAfter remains null } } } else if (arg.startsWith("-") //$NON-NLS-1$ && (arg.endsWith(".proxyHost") || arg.endsWith(".proxyPort") || arg //$NON-NLS-1$ //$NON-NLS-2$ .endsWith(".nonProxyHosts"))) //$NON-NLS-1$ { if (++idx < args.length) System.setProperty(arg.substring(1), args[idx]); } } } // We need to create a display first thing since many mechanisms // depend on its presence. // Display.setAppName("Materializer"); //$NON-NLS-1$ Display display = Display.getDefault(); HelpLinkErrorDialog.setSyncString(m_syncString); if (!Platform.getInstanceLocation().lock()) { errorCode = MaterializationConstants.ERROR_CODE_ALREADY_RUNNING_EXCEPTION; throw BuckminsterException.fromMessage(Messages.materializer_is_already_running); } BuckminsterPreferences.setLogLevelConsole(Logger.SILENT); BuckminsterPreferences.setLogLevelEclipseLogger(Logger.DEBUG); if (configUrl == null) { errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION; throw BuckminsterException .fromMessage(Messages.missing_required_argument_configURL_URL_to_config_properties); } Map<String, String> properties = new HashMap<String, String>(); InputStream propStream = null; try { URL propertiesURL = new URL(configUrl); propStream = new BufferedInputStream(propertiesURL.openStream()); Map<String, String> allProperties = new BMProperties(propStream); // Get rid of empty properties for (Map.Entry<String, String> entry : allProperties.entrySet()) { String value = entry.getValue(); if (!(value == null || value.trim().length() == 0)) properties.put(entry.getKey(), value); } } catch (IOException e) { errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION; throw BuckminsterException.fromMessage(e, Messages.can_not_read_materialization_information); } finally { IOUtils.close(propStream); } m_errorURL = properties.get(MaterializationConstants.PROP_ERROR_URL); if (m_errorURL == null) m_errorURL = MaterializationConstants.ERROR_HELP_URL; String errorMessage = properties.get(MaterializationConstants.PROP_ERROR_MESSAGE); if (errorMessage != null) { errorCode = MaterializationConstants.ERROR_CODE_404_EXCEPTION; throw BuckminsterException .fromMessage(new String(Base64.decodeBase64(errorMessage.getBytes()), "UTF-8")); //$NON-NLS-1$ } try { // Create the wizard dialog and resize it. // final InstallWizard installWizard = new InstallWizard(properties); m_errorURL = installWizard.getErrorURL(); AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~SWT.APPLICATION_MODAL); dialog.create(); // General exception handler Window.setExceptionHandler(new IExceptionHandler() { public void handleException(Throwable t) { if (t instanceof ThreadDeath) { // Don't catch ThreadDeath as this is a normal occurrence when // the thread dies throw (ThreadDeath) t; } IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t) .getStatus(); CorePlugin.logWarningsAndErrors(status); if (t instanceof JNLPException) { JNLPException je = (JNLPException) t; HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(), MaterializationConstants.ERROR_WINDOW_TITLE, je.getMessage(), MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, je.getErrorCode(), status); } else { HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(), MaterializationConstants.ERROR_WINDOW_TITLE, Messages.materializator_error, MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, ERROR_CODE_RUNTIME_EXCEPTION, status); } // Try to keep running. } }); final Shell shell = dialog.getShell(); shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH), Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT)); // when the shell is not started "ON TOP", it starts blinking shell.addShellListener(new ShellAdapter() { private int m_cnt = 0; @Override public void shellActivated(ShellEvent e) { if (m_cnt == 0) { Display.getDefault().asyncExec(new Runnable() { public void run() { shell.forceActive(); } }); m_cnt++; } } }); try { if (popupAfter != null) { long popupDelay = popupAfter.longValue() - (new Date()).getTime(); if (popupDelay > 0) Thread.sleep(popupDelay); } synchronizeWithBootstrap(); long popupDelay = DEFAULT_POPUP_DELAY; String popupDelayString = properties.get(MaterializationConstants.PROP_POPUP_DELAY); if (popupDelayString != null) { try { popupDelay = new Long(popupDelayString).longValue(); } catch (Throwable e) { popupDelay = DEFAULT_POPUP_DELAY; } } // need to wait a while until applet finishes Thread.sleep(popupDelay); dialog.open(); return OK_EXIT_CODE; } catch (Throwable e) { errorCode = ERROR_CODE_RUNTIME_EXCEPTION; final String finalErrorCode = errorCode; final IStatus status = BuckminsterException.wrap(e).getStatus(); CorePlugin.logWarningsAndErrors(status); Display.getDefault().syncExec(new Runnable() { public void run() { HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE, Messages.materialization_wizard_failed, MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, finalErrorCode, status); } }); return ERROR_EXIT_CODE; } } finally { display.dispose(); } } catch (Throwable e) { e.printStackTrace(); if (errorCode == null) { errorCode = ERROR_CODE_RUNTIME_EXCEPTION; } final String finalErrorCode = errorCode; final IStatus status = BuckminsterException.wrap(e).getStatus(); CorePlugin.logWarningsAndErrors(status); Display.getDefault().syncExec(new Runnable() { public void run() { HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE, Messages.materialization_cannot_be_started, MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, finalErrorCode, status); } }); return ERROR_EXIT_CODE; } }
From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java
public String dwnldAction() { dbgLog.fine("***** within dwnldAction() *****"); resetMsgDwnldButton();// www . j ava 2 s.co m if (checkDwnldParameters()) { FacesContext cntxt = FacesContext.getCurrentInstance(); HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse(); HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest(); StudyFile sf = dataTable.getStudyFile(); Long noRecords = dataTable.getRecordsPerCase(); String dsbUrl = getDsbUrl(); dbgLog.fine("dsbUrl=" + dsbUrl); String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath(); dbgLog.fine("serverPrefix" + serverPrefix); Map<String, List<String>> mpl = new HashMap<String, List<String>>(); // File inFile = new File(sf.getFileSystemLocation()); // File origFile = new File(inFile.getParent(), "_" + sf.getFileSystemName()); String formatType = (String) dwnldFileTypeSet.getValue(); dbgLog.fine("file type from the binding=" + formatType); if (formatType == null) { formatType = dwnldFileTypeSelected; dbgLog.fine("file type from the value=" + dwnldFileTypeSelected); } mpl.put("dtdwnld", Arrays.asList(formatType)); dbgLog.fine("citation info to be sent:\n" + getCitation()); mpl.put("studytitle", Arrays.asList(getStudyTitle())); dbgLog.fine("studyId=" + getStudyId().toString()); mpl.put("studyno", Arrays.asList(getStudyId().toString())); mpl.put("studyURL", Arrays.asList(studyURL)); mpl.put("", Arrays.asList("")); mpl.put("browserType", Arrays.asList(browserType)); mpl.put("recodedVarIdSet", getRecodedVarIdSet()); mpl.put("recodedVarNameSet", getRecodedVarNameSet()); mpl.put("recodedVarLabelSet", getRecodedVarLabelSet()); mpl.put("recodedVarTypeSet", getRecodedVariableType()); mpl.put("recodedVarBaseTypeSet", getBaseVariableTypeForRecodedVariable()); mpl.put("baseVarIdSet", getBaseVarIdSetFromRecodedVarIdSet()); mpl.put("baseVarNameSet", getBaseVarNameSetFromRecodedVarIdSet()); mpl.put("requestType", Arrays.asList("Download")); // Added by Matt Owen to find a way to sneak in Metadata that is lost between Rdata -> Tab mpl.put("originalFile", Arrays.asList(getOriginalFileSystemLocation().getAbsolutePath())); // ----------------------------------------------------- // Processing route, step by step: // // Step 0. Locate the data file and its attributes String fileId = sf.getId().toString(); String fileloc = sf.getFileSystemLocation(); String tabflnm = sf.getFileName(); boolean sbstOK = sf.isSubsettable(); String flct = sf.getFileType(); // Output debug statements dbgLog.info("location=" + fileloc); dbgLog.info("filename=" + tabflnm); dbgLog.info("subsettable=" + sbstOK); dbgLog.info("filetype=" + flct); dbgLog.info("studyUrl = " + studyURL); dbgLog.info("original file asbolute path = " + getOriginalFileSystemLocation().getAbsolutePath()); // D DvnRJobRequest sro = null; List<File> zipFileList = new ArrayList(); File tmpsbfl = null; if (sbstOK) { try { // this temp file will store the requested column(s): tmpsbfl = File.createTempFile("tempsubsetfile.", ".tab"); deleteTempFileList.add(tmpsbfl); // to produce this file, we'll either open the stream // and run our local subsetting code on it, or request // the subsetting to be performed natively by the access // driver, if it supports the functionality: // check whether a source file is tab-delimited or not boolean fieldcut = true; if ((noRecords != null) && (noRecords >= 1)) { fieldcut = false; } DataAccessRequest daReq = new DataAccessRequest(); daReq.setParameter("noVarHeader", "1"); DataAccessObject accessObject = DataAccess.createDataAccessObject(sf, daReq); if (accessObject.isSubsetSupported()) { dbgLog.fine("Using NATIVE subset functionality of the repository."); daReq.setParameter("vars", getVariableNamesForSubset()); accessObject.open(); InputStream inSubset = accessObject.getInputStream(); OutputStream outSubset = new BufferedOutputStream( new FileOutputStream(tmpsbfl.getAbsolutePath())); int bufsize = 8192; byte[] subsetDataBuffer = new byte[bufsize]; while ((bufsize = inSubset.read(subsetDataBuffer)) != -1) { outSubset.write(subsetDataBuffer, 0, bufsize); } inSubset.close(); outSubset.close(); // TODO: catch exceptions; reset the state of the page // if anything went wrong. See the fixed-field section // below for an example. } else { accessObject.open(); if (fieldcut) { // Cutting requested fields of data from a TAB-delimited stream: Set<Integer> fields = getFieldNumbersForSubsetting(); dbgLog.fine("subsetting fields=" + fields); // Create an instance of DvnJavaFieldCutter FieldCutter fc = new DvnJavaFieldCutter(); // Executes the subsetting request fc.subsetFile(accessObject.getInputStream(), tmpsbfl.getAbsolutePath(), fields, dataTable.getCaseQuantity(), "\t"); // TODO: catch exceptions; reset the state of the page // if anything went wrong. See the fixed-field section // below for an example. } else { // Cutting requested columns of data from a fixed-field stream: Map<Long, List<List<Integer>>> varMetaSet = getSubsettingMetaData(noRecords); DvnNewJavaFieldCutter fc = new DvnNewJavaFieldCutter(varMetaSet); try { //fc.cutColumns(new File(cutOp1), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath()); fc.cutColumns(accessObject.getInputStream(), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath()); } catch (FileNotFoundException e) { e.printStackTrace(); msgDwnldButton.setValue("* could not generate subset due to an IO problem"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to an IO problem "); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } catch (RuntimeException re) { re.printStackTrace(); msgDwnldButton.setValue("* could not generate subset due to an runtime error"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to an runtime error"); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } } } // Checks the resulting subset file: if (tmpsbfl.exists()) { Long subsetFileSize = tmpsbfl.length(); dbgLog.fine("subset file:Length=" + subsetFileSize); dbgLog.fine("subset file:name=" + tmpsbfl.getAbsolutePath()); if (subsetFileSize > 0) { mpl.put("subsetFileName", Arrays.asList(tmpsbfl.getAbsolutePath())); mpl.put("subsetDataFileName", Arrays.asList(tmpsbfl.getName())); } else { // subset file exists but it is empty msgDwnldButton.setValue("* an subset file is empty"); msgDwnldButton.setVisible(true); dbgLog.warning( "exiting dwnldAction() due to a subsetting error:" + "a subset file is empty"); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } } else { // subset file was not created msgDwnldButton.setValue("* a subset file was not created"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to a subsetting error:" + "a subset file was not created"); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } // If we've made it this far, we can increment the number of // downloads for the study file: VDC vdc = vdcService.getVDCFromRequest(req); GuestBookResponse guestbookResponse = (GuestBookResponse) getVDCSessionBean() .getGuestbookResponseMap().get("guestBookResponse_" + sf.getStudy().getId()); if (guestbookResponse == null) { //need to set up dummy network response guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(sf.getStudy(), sf, getVDCSessionBean().getLoginBean()); } guestbookResponse.setStudyVersion(sf.getStudy().getStudyVersionByNumber(versionNumber)); String jsessionId = null; Cookie cookies[] = req.getCookies(); for (int i = 0; i < cookies.length; i++) { if ("JSESSIONID".equals(cookies[i].getName())) { jsessionId = cookies[i].getValue(); } } if (jsessionId == null || "".equals(jsessionId)) { String[] stringArray = getVDCSessionBean().toString().split("@"); jsessionId = stringArray[1]; } guestbookResponse.setSessionId(jsessionId); String friendlyFormatName = ""; String formatRequestedMimeType = ""; if (formatType != null && !"".equals(formatType)) { if (formatType.equals("D00")) { formatRequestedMimeType = "text/tab-separated-values"; // tabular } else if (formatType.equals("D01")) { formatRequestedMimeType = "text/tab-separated-values"; // fixed-field } else { for (DataFileFormatType type : studyService.getDataFileFormatTypes()) { if (formatType.equals(type.getValue())) { formatRequestedMimeType = type.getMimeType(); } } } } if (formatRequestedMimeType == null || "".equals(formatRequestedMimeType)) { formatRequestedMimeType = "application/x-unknown"; } friendlyFormatName = FileUtil.getUserFriendlyTypeForMime(formatRequestedMimeType); guestbookResponse.setDownloadtype("Subsetting - " + friendlyFormatName); if (vdc != null) { studyService.incrementNumberOfDownloads(sf.getId(), vdc.getId(), (GuestBookResponse) guestbookResponse); } else { studyService.incrementNumberOfDownloads(sf.getId(), (Long) null, (GuestBookResponse) guestbookResponse); } // Step 3. Organizes parameters/metadata to be sent to the implemented // data-analysis-service class // skip the Rserve call completely (for plain tab file format, with no recoding)! -- L.A. if (!formatType.equals("D01") || (recodeSchema.size() > 0)) { Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables(); // New (as of 3.6): support for ordered categorical variables // (ingested from R ordered factors). // Note that this is only being added here, i.e., to the // download-and-save part; if/when we make the analysis // and statistics utilize/handle these ordered categories // in some special way, we'll need to add the actual // ordered values to the SRO objects there as well. -- L.A. Map<String, List<String>> categoryOrders = getCategoryValueOrdersForAllRequestedVariables(); if (categoryOrders != null) { sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema, categoryOrders, null); } else { sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema); } /* * Add the recoded -> base variable name map; (new as of v3.6;) * TODO: (?) do the same for the other action requests. * -- L.A. */ sro.setRecodedToBaseVar(getRecodedVarToBaseVarName()); // dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE)); // Step 4. Creates an instance of the the implemented // data-analysis-service class DvnRDataAnalysisServiceImpl das = new DvnRDataAnalysisServiceImpl(); // Executes a download or data analysis request and // stores the results in a Map <String, String> resultInfo = das.execute(sro); // Step 5. Check the exit status of the R process: if (resultInfo.get("RexecError").equals("true")) { msgDwnldButton.setValue("* The Request failed due to an R-runtime error"); msgDwnldButton.setVisible(true); dbgLog.fine("exiting dwnldAction() due to an R-runtime error"); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } } if (recodeSchema.size() > 0) { resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation()); } else { resultInfo.put("subsettingCriteria", "variables: " + getVariableNamesForSubset()); } } catch (MalformedURLException e) { e.printStackTrace(); msgDwnldButton.setValue("* file URL is malformed"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to a URL problem "); getVDCRequestBean().setSelectedTab("tabDwnld"); return ""; } catch (IOException e) { // this may occur if the dataverse is not released, // or if the file exists, but it is not accessible, etc. e.printStackTrace(); msgDwnldButton.setValue("* an IO problem occurred"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to an IO problem "); getVDCRequestBean().setSelectedTab("tabDwnld"); return ""; } // end of subset-OK case } else { // not subsettable data file msgDwnldButton.setValue("* this data file is not subsettable file"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction(): the data file is not subsettable "); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } // end:subsetNotOKcase // final processing steps for all successful cases // add study-metadata to the resultInfo map if (formatType.equals("D01") && !(recodeSchema.size() > 0)) { resultInfo.put("wbDataFileName", tmpsbfl.getAbsolutePath()); // Fields that would normally be populated by R: resultInfo.put("PID", "N/A"); resultInfo.put("R_min_verion_no", "N/A"); resultInfo.put("dsbHost", "N/A"); Date now = new Date(); resultInfo.put("RexecDate", now.toString()); } else { resultInfo.put("R_min_verion_no", resultInfo.get("Rversion").substring(2)); } resultInfo.put("offlineCitation", getCitation()); resultInfo.put("studyTitle", getStudyTitle()); resultInfo.put("studyNo", getStudyId().toString()); resultInfo.put("dtId", dtId.toString()); if (versionNumber != null) { resultInfo.put("versionNumber", versionNumber.toString()); } resultInfo.put("studyURL", studyURL); resultInfo.put("dataverse_version_no", dvnVersionNumber); resultInfo.put("option", "subset"); resultInfo.put("variableList", getVariableNamesForSubset()); // calculate UNF (locally, on the application side): List<DataVariable> subsetVariableList = getDataVariableForRequest(); String subsetUNFvalue = "[NOT CALCULATED]"; String[] unfValues = new String[subsetVariableList.size()]; for (int i = 0; i < subsetVariableList.size(); i++) { unfValues[i] = subsetVariableList.get(i).getUnf(); } dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues)); try { subsetUNFvalue = UNF5Util.calculateUNF(unfValues); } catch (NumberFormatException ex) { // if anything went wrong during the UNF calculation, it's not // a fatal condition; we'll just be displaying "not calculated" // instead of the UNF in the final README file. dbgLog.fine("error while trying to calculate subset UNF: Number Format Exception."); ex.printStackTrace(); } catch (IOException ex) { dbgLog.fine("error while trying to calculate subset UNF: IO Exception."); ex.printStackTrace(); } resultInfo.put("fileUNF", subsetUNFvalue); // writing necessary files: try { if (formatType.equals("D01") && !(recodeSchema.size() > 0)) { // (2) tab-delimited-format-only step: // // In the final zip file we package the subset file // and a replication README file (also contains citation). // We also *used to* include the SAS, SPSS and R control // files created by R. We are not doing this anymore, but // I left the code commented-out below. // -- L.A. Jan. 2012 // // We are also adding the variable header to the file here. /* SKIP CODE FILES -- L.A. String codeFileSas = "codeFile_sas_" + resultInfo.get("PID") + ".sas"; File tmpCCsasfl = new File(TEMP_DIR, codeFileSas); deleteTempFileList.add(tmpCCsasfl); zipFileList.add(tmpCCsasfl); String codeFileSpss = "codeFile_spss_" + resultInfo.get("PID") + ".sps"; File tmpCCspsfl = new File(TEMP_DIR, codeFileSpss); deleteTempFileList.add(tmpCCspsfl); zipFileList.add(tmpCCspsfl); String codeFileStata = "codeFile_stata_" + resultInfo.get("PID") + ".do"; File tmpCCdofl = new File(TEMP_DIR, codeFileStata); deleteTempFileList.add(tmpCCdofl); zipFileList.add(tmpCCdofl); StatisticalCodeFileWriter scfw = new StatisticalCodeFileWriter(sro); scfw.write(tmpCCsasfl, tmpCCspsfl, tmpCCdofl); */ // add the subset file: File tmpsbflnew = File.createTempFile("tempsubsetfile_new.", ".tab"); deleteTempFileList.add(tmpsbflnew); InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl)); OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew)); String varHeaderLine = getVariableHeaderForSubset(); // Add the variable header to the subset file: byte[] varHeaderBuffer = null; varHeaderBuffer = varHeaderLine.getBytes(); outb.write(varHeaderBuffer); outb.flush(); int bufsize; byte[] bffr = new byte[8192]; while ((bufsize = inb.read(bffr)) != -1) { outb.write(bffr, 0, bufsize); } inb.close(); outb.close(); dbgLog.fine("adding tab file: " + tmpsbflnew.getName()); zipFileList.add(tmpsbflnew); } else { // (2)The format-converted subset data file String wbDataFileName = resultInfo.get("wbDataFileName"); dbgLog.fine("wbDataFileName=" + wbDataFileName); File wbSubsetDataFile = new File(wbDataFileName); if (wbSubsetDataFile.exists()) { dbgLog.fine("wbSubsetDataFile:length=" + wbSubsetDataFile.length()); deleteTempFileList.add(wbSubsetDataFile); zipFileList.add(wbSubsetDataFile); } else { // the data file was not created dbgLog.fine("wbSubsetDataFile does not exist"); msgDwnldButton.setValue("* The requested data file is not available"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction(): data file was not transferred"); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } } // Create README file: String readMeFileName = null; if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) { readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt"; } else { readMeFileName = REP_README_FILE_PREFIX + fileId + ".txt"; } File readMeFile = new File(TEMP_DIR, readMeFileName); DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo); rw.writeREADMEfile(readMeFile, true); zipFileList.add(readMeFile); deleteTempFileList.add(readMeFile); for (File f : zipFileList) { dbgLog.fine("file to zip: path=" + f.getAbsolutePath() + "\tname=" + f.getName()); } // We can now zip all the required files" try { String zipFilePrefix = null; if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) { zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip"; } else { zipFilePrefix = "zipFile_" + fileId + ".zip"; } File zipFile = new File(TEMP_DIR, zipFilePrefix); //deleteTempFileList.add(zipFile); String zfname = zipFile.getName(); zipFileName = zfname; zipFiles(new FileOutputStream(zipFile), zipFileList); /* try { Thread.sleep(1000); } catch (Exception e) { } */ zipResourceDynFileName = new ByteArrayResource( toByteArray(new FileInputStream(zipFile.getAbsolutePath()))); dbgLog.info("Subsetting: zipFileName=" + zipFileName); dbgLog.info("Subsetting: zipFile, absolute path: " + zipFile.getAbsolutePath()); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); // Hide 'Create' button, show 'Download' button: dwnldButton.setRendered(false); dwnloadSubsetButton.setRendered(true); dbgLog.info("***** within dwnldAction(): ends here *****"); /* * Navigation: * - is it necessary to use "faces-redirect" navigation here? * Or should we simply return "" as long as we want to stay * on the subsetting page? if (versionNumber != null) { return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId + "&versionNumber=" + versionNumber; } return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId; */ return ""; } catch (IOException e) { // file-access problem, etc. e.printStackTrace(); dbgLog.fine("download zipping IO exception"); msgDwnldButton.setValue("* an IO problem occurred"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to an IO problem "); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } // end of zipping step } catch (IOException e) { e.printStackTrace(); msgDwnldButton.setValue("* an IO problem occurred"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to an IO problem "); getVDCRequestBean().setSelectedTab("tabDwnld"); dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME); return ""; } // end: params are OK-case } else { // the selection is incomplete // show error message; pgDwnldErrMsg.setRendered(true); msgDwnldButton.setValue("* Error: Select a file format"); msgDwnldButton.setVisible(true); dbgLog.warning("exiting dwnldAction() due to incomplete data "); getVDCRequestBean().setSelectedTab("tabDwnld"); return ""; } // end: checking params }
From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { //String fisTmpFile = null; PDFAsVisualSignatureProperties properties = null; if (!(genericPdfObject instanceof PDFBOXObject)) { // tODO:// w ww .ja v a 2s .co m throw new PdfAsException(); } PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { // tODO: throw new PdfAsException(); } PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; String pdfaVersion = null; PDDocument doc = null; SignatureOptions options = new SignatureOptions(); COSDocument visualSignatureDocumentGuard = null; try { doc = pdfObject.getDocument(); SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings()); TablePos tablePos = null; if (signaturePlaceholderData != null) { // Placeholder found! logger.info("Placeholder data found."); if (signaturePlaceholderData.getProfile() != null) { logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile()); requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile()); } tablePos = signaturePlaceholderData.getTablePos(); if (tablePos != null) { SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); float minWidth = signatureProfileConfiguration.getMinWidth(); if (minWidth > 0) { if (tablePos.getWidth() < minWidth) { tablePos.width = minWidth; logger.debug("Correcting placeholder with to minimum width {}", minWidth); } } logger.debug("Placeholder Position set to: " + tablePos.toString()); } } PDSignature signature = new PDSignature(); signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default // filter signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter())); SignatureProfileSettings signatureProfileSettings = TableFactory .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); /* * Check if input document is PDF-A conform * if (signatureProfileSettings.isPDFA()) { // TODO: run preflight parser runPDFAPreflight(pdfObject.getOriginalDocument()); } */ ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus()); String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings); signature.setName(signerName); // take signing time from provided signer... signature.setSignDate(signer.getSigningDate()); // ...and update operation status in order to use exactly this date for the complete signing process requestedSignature.getStatus().setSigningDate(signer.getSigningDate()); String signerReason = signatureProfileSettings.getSigningReason(); if (signerReason == null) { signerReason = "PAdES Signature"; } signature.setReason(signerReason); logger.debug("Signing reason: " + signerReason); logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); // the signing date, needed for valid signature // signature.setSignDate(signer.getSigningDate()); signer.setPDSignature(signature); int signatureSize = 0x1000; try { String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); if (reservedSignatureSizeString != null) { signatureSize = Integer.parseInt(reservedSignatureSizeString); } logger.debug("Reserving {} bytes for signature", signatureSize); } catch (NumberFormatException e) { logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); } options.setPreferredSignatureSize(signatureSize); if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { pdfaVersion = getPDFAVersion(doc); signatureProfileSettings.setPDFAVersion(pdfaVersion); } // Is visible Signature if (requestedSignature.isVisual()) { logger.debug("Creating visual signature block"); SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); if (tablePos == null) { // ================================================================ // PositioningStage (visual) -> find position or use // fixed // position String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition(); TablePos signaturePos = null; String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); if (signaturePosString != null) { logger.debug("using signature Positioning: " + signaturePos); signaturePos = new TablePos(signaturePosString); } logger.debug("using Positioning: " + posString); if (posString != null) { // Merge Signature Position tablePos = new TablePos(posString, signaturePos); } else { // Fallback to signature Position! tablePos = signaturePos; } if (tablePos == null) { // Last Fallback default position tablePos = new TablePos(); } } //Legacy Modes not supported with pdfbox2 anymore // boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); // boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning(); // create Table describtion Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); /* * PDDocument originalDocument = PDDocument .load(new * ByteArrayInputStream(pdfObject.getStatus() * .getPdfObject().getOriginalDocument())); */ PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "", doc, visualObject, pdfObject.getStatus().getSettings()); logger.debug("Positioning: {}", positioningInstruction.toString()); if (positioningInstruction.isMakeNewPage()) { int last = doc.getNumberOfPages() - 1; PDDocumentCatalog root = doc.getDocumentCatalog(); PDPage lastPage = root.getPages().get(last); root.getPages().getCOSObject().setNeedToBeUpdated(true); PDPage p = new PDPage(lastPage.getMediaBox()); p.setResources(new PDResources()); p.setRotation(lastPage.getRotation()); doc.addPage(p); } // handle rotated page int targetPageNumber = positioningInstruction.getPage(); logger.debug("Target Page: " + targetPageNumber); PDPage targetPage = doc.getPages().get(targetPageNumber - 1); int rot = targetPage.getRotation(); logger.debug("Page rotation: " + rot); // positioningInstruction.setRotation(positioningInstruction.getRotation() // + rot); logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); position.setY(positioningInstruction.getY()); position.setPage(positioningInstruction.getPage()); position.setHeight(visualObject.getHeight()); position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings); properties.buildSignature(); /* * ByteArrayOutputStream sigbos = new * ByteArrayOutputStream(); * sigbos.write(StreamUtils.inputStreamToByteArray * (properties .getVisibleSignature())); sigbos.close(); */ if (signaturePlaceholderData != null) { // Placeholder found! // replace placeholder URL fileUrl = PADESPDFBOXSigner.class.getResource("/placeholder/empty.jpg"); PDImageXObject img = PDImageXObject.createFromFile(fileUrl.getPath(), doc); img.getCOSObject().setNeedToBeUpdated(true); // PDDocumentCatalog root = doc.getDocumentCatalog(); // PDPageNode rootPages = root.getPages(); // List<PDPage> kids = new ArrayList<PDPage>(); // rootPages.getAllKids(kids); int pageNumber = positioningInstruction.getPage(); PDPage page = doc.getPages().get(pageNumber - 1); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); COSDictionary xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject() .getDictionaryObject(COSName.XOBJECT); xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img); xobjectsDictionary.setNeedToBeUpdated(true); page.getResources().getCOSObject().setNeedToBeUpdated(true); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); } if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { PDDocumentCatalog root = doc.getDocumentCatalog(); COSBase base = root.getCOSObject().getItem(COSName.OUTPUT_INTENTS); if (base == null) { InputStream colorProfile = null; try { colorProfile = PDDocumentCatalog.class .getResourceAsStream("/icm/sRGB Color Space Profile.icm"); try { PDOutputIntent oi = new PDOutputIntent(doc, colorProfile); oi.setInfo("sRGB IEC61966-2.1"); oi.setOutputCondition("sRGB IEC61966-2.1"); oi.setOutputConditionIdentifier("sRGB IEC61966-2.1"); oi.setRegistryName("http://www.color.org"); root.addOutputIntent(oi); root.getCOSObject().setNeedToBeUpdated(true); logger.info("added Output Intent"); } catch (Throwable e) { e.printStackTrace(); throw new PdfAsException("Failed to add Output Intent", e); } } finally { IOUtils.closeQuietly(colorProfile); } } } options.setPage(positioningInstruction.getPage()); options.setVisualSignature(properties.getVisibleSignature()); } visualSignatureDocumentGuard = options.getVisualSignature(); doc.addSignature(signature, signer, options); String sigFieldName = signatureProfileSettings.getSignFieldValue(); if (sigFieldName == null) { sigFieldName = "PDF-AS Signatur"; } int count = PdfBoxUtils.countSignatures(doc, sigFieldName); sigFieldName = sigFieldName + count; PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); // PDStructureTreeRoot pdstRoot = // doc.getDocumentCatalog().getStructureTreeRoot(); // COSDictionary dic = // doc.getDocumentCatalog().getCOSDictionary(); // PDStructureElement el = new PDStructureElement("Widget", // pdstRoot); PDSignatureField signatureField = null; if (acroFormm != null) { @SuppressWarnings("unchecked") List<PDField> fields = acroFormm.getFields(); if (fields != null) { for (PDField pdField : fields) { if (pdField != null) { if (pdField instanceof PDSignatureField) { PDSignatureField tmpSigField = (PDSignatureField) pdField; if (tmpSigField.getSignature() != null && tmpSigField.getSignature().getCOSObject() != null) { if (tmpSigField.getSignature().getCOSObject() .equals(signature.getCOSObject())) { signatureField = (PDSignatureField) pdField; } } } } } } else { logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); } if (signatureField != null) { signatureField.setPartialName(sigFieldName); } if (properties != null) { signatureField.setAlternateFieldName(properties.getAlternativeTableCaption()); } else { signatureField.setAlternateFieldName(sigFieldName); } } else { logger.warn("Failed to name Signature Field! [Cannot find acroForm!]"); } // PDF-UA logger.info("Adding pdf/ua content."); try { PDDocumentCatalog root = doc.getDocumentCatalog(); PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); if (structureTreeRoot != null) { logger.info("Tree Root: {}", structureTreeRoot.toString()); List<Object> kids = structureTreeRoot.getKids(); if (kids == null) { logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); } PDStructureElement docElement = null; for (Object k : kids) { if (k instanceof PDStructureElement) { docElement = (PDStructureElement) k; break; } } PDStructureElement sigBlock = new PDStructureElement("Form", docElement); // create object dictionary and add as child element COSDictionary objectDic = new COSDictionary(); objectDic.setName("Type", "OBJR"); objectDic.setItem("Pg", signatureField.getWidget().getPage()); objectDic.setItem("Obj", signatureField.getWidget()); List<Object> l = new ArrayList<Object>(); l.add(objectDic); sigBlock.setKids(l); sigBlock.setPage(signatureField.getWidget().getPage()); sigBlock.setTitle("Signature Table"); sigBlock.setParent(docElement); docElement.appendKid(sigBlock); // Create and add Attribute dictionary to mitigate PAC // warning COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject(); COSDictionary sub = new COSDictionary(); sub.setName("O", "Layout"); sub.setName("Placement", "Block"); sigBlockDic.setItem(COSName.A, sub); sigBlockDic.setNeedToBeUpdated(true); // Modify number tree PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey(); if (ntn == null) { ntn = new PDNumberTreeNode(objectDic, null); logger.info("No number-tree-node found!"); } COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS); COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS); if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array //create dictionary with limits and nums array COSDictionary pTreeEntry = new COSDictionary(); COSArray limitsArray = new COSArray(); //limits for exact one entry limitsArray.add(COSInteger.get(parentTreeNextKey)); limitsArray.add(COSInteger.get(parentTreeNextKey)); COSArray numsArray = new COSArray(); numsArray.add(COSInteger.get(parentTreeNextKey)); numsArray.add(sigBlock); pTreeEntry.setItem(COSName.NUMS, numsArray); pTreeEntry.setItem(COSName.LIMITS, limitsArray); PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); ntnKids.add(newKidsElement); ntnKids.setNeedToBeUpdated(true); } else if (ntnNumbers != null && ntnKids == null) { int arrindex = ntnNumbers.size(); ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); ntnNumbers.setNeedToBeUpdated(true); structureTreeRoot.setParentTree(ntn); } else if (ntnNumbers == null && ntnKids == null) { //document is not pdfua conform before signature creation throw new PdfAsException("error.pdf.sig.pdfua.1"); } else { //this is not allowed throw new PdfAsException("error.pdf.sig.pdfua.1"); } // set StructureParent for signature field annotation signatureField.getWidget().setStructParent(parentTreeNextKey); //Increase the next Key value in the structure tree root structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); // add the Tabs /S Element for Tabbing through annots PDPage p = signatureField.getWidget().getPage(); p.getCOSObject().setName("Tabs", "S"); p.getCOSObject().setNeedToBeUpdated(true); //check alternative signature field name if (signatureField != null) { if (signatureField.getAlternateFieldName().equals("")) signatureField.setAlternateFieldName(sigFieldName); } ntn.getCOSObject().setNeedToBeUpdated(true); sigBlock.getCOSObject().setNeedToBeUpdated(true); structureTreeRoot.getCOSObject().setNeedToBeUpdated(true); objectDic.setNeedToBeUpdated(true); docElement.getCOSObject().setNeedToBeUpdated(true); } } catch (Throwable e) { if (signatureProfileSettings.isPDFUA() == true) { logger.error("Could not create PDF-UA conform document!"); throw new PdfAsException("error.pdf.sig.pdfua.1", e); } else { logger.info("Could not create PDF-UA conform signature"); } } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); synchronized (doc) { doc.saveIncremental(bos); byte[] outputDocument = bos.toByteArray(); /* Check if resulting pdf is PDF-A conform */ //if (signatureProfileSettings.isPDFA()) { // // TODO: run preflight parser // runPDFAPreflight(outputDocument); //} pdfObject.setSignedDocument(outputDocument); } } finally { if (options != null) { if (options.getVisualSignature() != null) { options.getVisualSignature().close(); } } } System.gc(); } catch (IOException e) { logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e); throw new PdfAsException("error.pdf.sig.01", e); } finally { if (doc != null) { try { doc.close(); } catch (IOException e) { logger.debug("Failed to close COS Doc!", e); // Ignore } } logger.debug("Signature done!"); } }
From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java
public void adjuntar(ActionEvent event) { try {//from www .j ava 2s. c o m if (event != null) { if (StringUtils.isBlank(this.getTipoContenido())) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Seleccione el tipo de contenido a adjuntar."); FacesContext.getCurrentInstance().addMessage(null, message); return; } if (this.getUploadFile() == null) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Debe Cargar el archivo antes de adjuntar."); FacesContext.getCurrentInstance().addMessage(null, message); return; } ResourceBundle bundle = ResourceBundle.getBundle(Parameters.getMessages()); String tipoDocumento = bundle.getString("tipoDocumento"); String tipoVideo = bundle.getString("tipoVideo"); String tipoAudio = bundle.getString("tipoAudio"); String tipoImagen = bundle.getString("tipoImagen"); String tipoArchivo = bundle.getString("tipoArchivo"); String tipoLink = bundle.getString("tipoLink"); String tipoOtro = bundle.getString("tipoOtro"); String tmppath = bundle.getString("temppath"); String filename = this.getUploadFile().getFileName(); String contentType = this.getUploadFile().getContentType(); String contentTypePdf = bundle.getString("contentTypePdf"); String contentTypeWord = bundle.getString("contentTypeWord"); String contentTypeExcel = bundle.getString("contentTypeExcel"); String contentTypePowerPoint = bundle.getString("contentTypePowerPoint"); String contentTypeWordx = bundle.getString("contentTypeWordx"); String contentTypeExcelx = bundle.getString("contentTypeExcelx"); String contentTypePowerPointx = bundle.getString("contentTypePowerPointx"); String contentTypeMpg = bundle.getString("contentTypeMpg"); String contentTypeAvi = bundle.getString("contentTypeAvi"); String contentTypeMp4 = bundle.getString("contentTypeMp4"); String contentTypeQuickTime = bundle.getString("contentTypeQuickTime"); String contentTypeMp3 = bundle.getString("contentTypeMp3"); String contentTypeMp3_ = bundle.getString("contentTypeMp3_"); String contentTypeWav = bundle.getString("contentTypeWav"); String contentTypeGif = bundle.getString("contentTypeGif"); String contentTypeJpg = bundle.getString("contentTypeJpg"); String contentTypePng = bundle.getString("contentTypePng"); String contentTypeTiff = bundle.getString("contentTypeTiff"); String contentTypePlain = bundle.getString("contentTypePlain"); String contentTypeRichtext = bundle.getString("contentTypeRichtext"); String contentTypeXml = bundle.getString("contentTypeXml"); String contentTypeHtml = bundle.getString("contentTypeHtml"); String contentTypeLink = bundle.getString("contentTypeLink"); if (this.getTipoContenido().equals(tipoDocumento)) { if (!contentType.equals(contentTypePdf) && !contentType.equals(contentTypeWord) && !contentType.equals(contentTypeExcel) && !contentType.equals(contentTypePowerPoint) && !contentType.equals(contentTypeWordx) && !contentType.equals(contentTypeExcelx) && !contentType.equals(contentTypePowerPointx)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } if (this.getTipoContenido().equals(tipoVideo)) { if (!contentType.equals(contentTypeMpg) && !contentType.equals(contentTypeAvi) && !contentType.equals(contentTypeMp4) && !contentType.equals(contentTypeQuickTime)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } if (this.getTipoContenido().equals(tipoAudio)) { if (!contentType.equals(contentTypeMp3) && !contentType.equals(contentTypeMp3_) && !contentType.equals(contentTypeWav)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } if (this.getTipoContenido().equals(tipoImagen)) { if (!contentType.equals(contentTypeGif) && !contentType.equals(contentTypeJpg) && !contentType.equals(contentTypePng) && !contentType.equals(contentTypeTiff)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } if (this.getTipoContenido().equals(tipoArchivo)) { if (!contentType.equals(contentTypePlain) && !contentType.equals(contentTypeRichtext) && !contentType.equals(contentTypeXml) && !contentType.equals(contentTypeHtml)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } if (this.getTipoContenido().equals(tipoLink)) { if (!contentType.equals(contentTypeLink)) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.", "Formato de archivo incorrecto!."); FacesContext.getCurrentInstance().addMessage(null, message); return; } } ArchivoConocimiento archivoconocimiento = new ArchivoConocimiento(); archivoconocimiento.setUploadedFile(this.getUploadFile()); archivoconocimiento.setVnombre(filename); archivoconocimiento.setNtipoarchivo(BigDecimal.valueOf(Long.parseLong(this.getTipoContenido()))); archivoconocimiento.setVcontenttype(contentType); archivoconocimiento.setVruta(tmppath + filename); archivoconocimiento.setFile(new File(archivoconocimiento.getVruta())); archivoconocimiento.setContent(new DefaultStreamedContent( new FileInputStream(archivoconocimiento.getFile()), contentType, filename)); this.getListaArchivos().add(archivoconocimiento); } } catch (NumberFormatException e) { log.error(e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
/** * Gets the associated row numbers.// w ww . j a va 2 s .c o m * * @param table * the table * @param rowList * the row list * @return the associated row numbers */ private int[] getAssociatedRowNumbers(final DataTable table, final String rowList) { int[] rowNumbers = null; try { if (rowList.equalsIgnoreCase("ALL")) { int rowCount = table.getRowCount(); rowNumbers = new int[rowCount]; for (int i = 0; i < rowCount; i++) { rowNumbers[i] = i; } } else if (rowList.contains("-")) { String[] range = rowList.split("-"); int start = Integer.parseInt(range[0]); int end = Integer.parseInt(range[1]); rowNumbers = new int[((end - start)) + 1]; int rowNumberIndex = 0; for (int i = start; i <= end; i++) { rowNumbers[rowNumberIndex] = i; rowNumberIndex++; } } else if (rowList.contains(",")) { String[] range = rowList.split(","); rowNumbers = new int[range.length]; for (int i = 0; i < range.length; i++) { rowNumbers[i] = Integer.parseInt(range[i]); } } else { rowNumbers = new int[] { Integer.parseInt(rowList) }; } } catch (NumberFormatException e) { e.printStackTrace(); String errString = e.getMessage(); reportresult(true, "DATA TABLE ITERATION :", "FAILED", "Cannot iterate over the data table. Cannot parse the row numbers : " + rowList + ". Actual Error : " + errString); checkTrue(false, true, "Cannot iterate over the data table. Cannot parse the row numbers : " + rowList + ". Actual Error : " + errString); } catch (IndexOutOfBoundsException e) { String errString = e.getMessage(); reportresult(true, "DATA TABLE ITERATION :", "FAILED", "Cannot iterate over the data table. Actual Error : " + errString); checkTrue(false, true, "Cannot iterate over the data table. Actual Error : " + errString); } return rowNumbers; }
From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java
/** * //from w w w. jav a2 s . co m * ??dvr sn * * @param row * * @param rowIndex * * @return standardNumber * @author wangbinyu * <p /> * Create at 2013 ?10:52:45 */ private String findDvrNumber(Row row, int rowIndex) { Cell cell = row.getCell(7); row.getCell(7).setCellType(Cell.CELL_TYPE_STRING); String dvrNumberString = cell.getStringCellValue(); Long dvrNumber = null; if (StringUtils.isBlank(dvrNumberString)) { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 8 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.PARAMETER_NULL + ",dvrNumber is not null"); } else { try { dvrNumber = Long.parseLong(dvrNumberString); } catch (NumberFormatException n) { n.printStackTrace(); throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 8 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR + ",parameter dvrNumber[" + dvrNumberString + "] invalid !"); } } return dvrNumber + ""; }
From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java
private String isDvrNumber(Row row, int rowIndex, List<String> dvrNumbers) { Cell cell = row.getCell(11);/* w w w . ja v a2 s .c o m*/ Long dvrNumber = null; if (cell == null) { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 12 + "," + TypeDefinition.DVR_TEMPLATE + "," + TypeDefinition.PARAMETER_NULL + ",dvrNumber is not null"); } else { try { row.getCell(11).setCellType(Cell.CELL_TYPE_STRING); String dn = cell.getStringCellValue(); if (dvrNumbers.size() > 0) { if (dvrNumbers.contains(dn)) { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 12 + "," + TypeDefinition.DVR_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR + ",parameter dvrNumber[" + dn + "] invalid !"); } dvrNumber = Long.parseLong(dn); } } catch (NumberFormatException n) { n.printStackTrace(); throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 12 + "," + TypeDefinition.DVR_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR + ",parameter dvrNumber[" + cell.getStringCellValue() + "] invalid !"); } } return dvrNumber + ""; }
From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java
/** * // ww w . j ava2 s.com * dvr????????????dvr?? * * @param row * * @param cameraNumber * ?? * @param dvr * dvr * @param rowIndex * ? * @param arrayChannelAmount * dvr? * @author wangbinyu * <p /> * Create at 2013 ?3:39:57 */ private void isExistChannelNumber(Row row, Dvr dvr, int rowIndex, List<TemplateDvrIsChannelNumberVO> tdcs) { int arrayChannelAmount[] = null; for (int i = 0; i < tdcs.size(); i++) { if (row.getCell(7).getStringCellValue().equals(tdcs.get(i).getDvrNumber())) { arrayChannelAmount = tdcs.get(i).getArrayChannelAmount(); break; } } int channelAmount = dvr.getChannelAmount(); Cell cell = row.getCell(3); int channelNumber = 0; if (cell == null) { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.PARAMETER_NULL + ",channelNumber is not null"); } else { try { row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); channelNumber = Integer.parseInt(cell.getStringCellValue()); } catch (NumberFormatException n) { n.printStackTrace(); throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.PARAMETER_ERROR + ",parameter channelNumber[" + cell.getStringCellValue() + "] invalid !"); } } if (channelNumber > channelAmount) { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.CAMERA_OVER_LIMIT + ",Channel amount[" + channelAmount + "] over limit !"); } if (channelNumber == arrayChannelAmount[channelNumber - 1]) { arrayChannelAmount[channelNumber - 1] = -1; } else { throw new BusinessException(ErrorCode.EXCEL_CONTENT_ERROR, "excel row:" + (rowIndex + 1) + ",cellIndex:" + 4 + "," + TypeDefinition.CAMERA_TEMPLATE + "," + TypeDefinition.CAMERA_CHANNEL_NUMBER_EXIST + ",channelId[" + channelNumber + "] is already exist !"); } }