List of usage examples for java.lang NullPointerException printStackTrace
public void printStackTrace(PrintStream s)
From source file:org.objectweb.proactive.core.ssh.SSHClient.java
public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption(OPT_PASSWORD, true, "Password for password authentication"); options.addOption(OPT_USERNAME, true, "Username"); options.addOption(OPT_IDENTITY, true, "Identity file"); options.addOption(OPT_IDENTITY_PASSWORD, true, "Password for identity file"); options.addOption(OPT_HELP, false, "Help"); options.addOption(OPT_VERBOSE, false, "Verbose"); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); String username = System.getProperty("user.name"); String password = null;/*from ww w . j a v a 2s. c o m*/ File identity = null; String identityPassword = null; String hostname = null; if (cmd.hasOption(OPT_HELP)) { printHelp(true); } if (cmd.hasOption(OPT_USERNAME)) { username = cmd.getOptionValue(OPT_USERNAME); } if (cmd.hasOption(OPT_PASSWORD)) { password = cmd.getOptionValue(OPT_PASSWORD); } if (cmd.hasOption(OPT_IDENTITY)) { identity = new File(cmd.getOptionValue(OPT_IDENTITY)); if (!identity.exists()) { System.err.println("[E] specified identity file," + identity + ", does not exist"); System.exit(EXIT_ERROR); } if (!identity.isFile()) { System.err.println("[E] specified identity file" + identity + " is not a file"); System.exit(EXIT_ERROR); } if (!identity.canRead()) { System.err.println("[E] specified identity file" + identity + " is not readable"); System.exit(EXIT_ERROR); } } if (cmd.hasOption(OPT_IDENTITY_PASSWORD)) { identityPassword = cmd.getOptionValue(OPT_IDENTITY_PASSWORD); } if (cmd.hasOption(OPT_VERBOSE)) { verbose = true; } List<String> remArgs = cmd.getArgList(); if (remArgs.size() == 0) { System.err.println("[E] You must specify an hostname"); printHelp(true); } hostname = remArgs.remove(0); int exitCode = EXIT_ERROR; try { Connection conn = new Connection(hostname); conn.connect(); boolean isAuthenticated = false; // 1. Password authentication requested if (password != null) { isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated) { info("Password authentication succeeded"); } else { info("Password authentication failed"); } } else { // 2. Pubkey authentication // 2.1 An identity file is specified use it if (identity != null) { isAuthenticated = conn.authenticateWithPublicKey(username, identity, identityPassword); if (isAuthenticated) { info("Pubkey authentication succeeded with " + identity); } else { info("Pubkey authentication failed with " + identity); } } else { // 2.2 Try to find identity files automagically SshConfig config = new SshConfig(); SSHKeys keys = new SSHKeys(config.getKeyDir()); for (String id : keys.getKeys()) { File f = new File(id); if (!(f.exists() && f.isFile() && f.canRead())) { continue; } isAuthenticated = conn.authenticateWithPublicKey(username, f, identityPassword); info("Pubkey authentication succeeded with " + f); if (isAuthenticated) { break; } } } } if (!isAuthenticated) { System.err.println("[E] Authentication failed"); System.exit(2); } conn.setTCPNoDelay(true); Session sess = conn.openSession(); sess.execCommand(buildCmdLine(remArgs)); InputStream stdout = sess.getStdout(); InputStream stderr = sess.getStderr(); byte[] buffer = new byte[8192]; while (true) { if ((stdout.available() == 0) && (stderr.available() == 0)) { /* Even though currently there is no data available, it may be that new data arrives * and the session's underlying channel is closed before we call waitForCondition(). * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may * be set together. */ int conditions = sess.waitForCondition( ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 0); /* Wait no longer than 2 seconds (= 2000 milliseconds) */ if ((conditions & ChannelCondition.TIMEOUT) != 0) { /* A timeout occured. */ throw new IOException("Timeout while waiting for data from peer."); } /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */ if ((conditions & ChannelCondition.EOF) != 0) { /* The remote side won't send us further data... */ if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { // PROACTIVE-879: Ugly fix // Calling Session.getExitStatus() can throw an NPE for an unknown reason // After some investigation, I noticed that a subsequent call to this method could succeed // So we try to call session.getExitStatus() until it does not throw an NPE or the timeout expires TimeoutAccounter ta = TimeoutAccounter.getAccounter(1000); while (!ta.isTimeoutElapsed()) { try { exitCode = sess.getExitStatus(); break; } catch (NullPointerException e) { Thread.yield(); } } break; } } /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */ // You can be paranoid and check that the library is not going nuts: // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) // throw new IllegalStateException("Unexpected condition result (" + conditions + ")"); } /* If you below replace "while" with "if", then the way the output appears on the local * stdout and stder streams is more "balanced". Addtionally reducing the buffer size * will also improve the interleaving, but performance will slightly suffer. * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =) */ while (stdout.available() > 0) { int len = stdout.read(buffer); if (len > 0) { // this check is somewhat paranoid System.out.write(buffer, 0, len); } } while (stderr.available() > 0) { int len = stderr.read(buffer); if (len > 0) { // this check is somewhat paranoid System.err.write(buffer, 0, len); } } } sess.close(); conn.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(EXIT_ERROR); } System.exit(exitCode); }
From source file:org.polarsys.reqcycle.ui.eattrpropseditor.EAttrPropsEditorPlugin.java
private static IEAttrPropsEditor<?> getEditorByTypeInstance(Class<?> initialClass) { try {/*from w ww . jav a 2s .c om*/ Class<?> nearestClass = null; for (final Class<?> currentSupportedClass : getEAttrEditorManager().keySet()) { if (currentSupportedClass.isAssignableFrom(initialClass)) { if (nearestClass == null || (nearestClass.isAssignableFrom(currentSupportedClass))) { nearestClass = currentSupportedClass; } if (nearestClass.equals(initialClass)) break; } } if (nearestClass != null) { return getEAttrEditorManager().get(nearestClass).create(); } } catch (NullPointerException e) { e.printStackTrace(System.err); // XXX Change or remove } return null; }
From source file:de.xplib.xdbm.ui.Application.java
public static InternalFramePanel openPanel(final String nameIn) { Application app = Application.getInstance(); PluginFile p = app.getConfig().getPluginFile(nameIn); InternalFramePanel ifp = null;//from w ww . j a v a 2 s . co m try { Plugin plugin = p.createPlugin(); if (plugin.hasPanel()) { ifp = plugin.getPanelInstance(app); } } catch (NullPointerException e) { e.printStackTrace(Application.err); } catch (FileNotFoundException e) { e.printStackTrace(Application.err); } catch (ClassCastException e) { e.printStackTrace(Application.err); } catch (ClassNotFoundException e) { e.printStackTrace(Application.err); } if (ifp != null && ifp.getParent() == null) { InternalFrame[] frames = Application.getInstance().getInternalFrames(); for (int i = 0; i < frames.length; i++) { if (frames[i].getPosition().equals(p.getPosition())) { ((JTabbedPane) frames[i].getContent()).addTab("", ifp); } } } return ifp; }
From source file:gate.util.Files.java
/** * This method takes a regular expression and a directory name and returns * the set of Files that match the pattern under that directory. * * @param regex regular expression path that begins with <code>pathFile</code> * @param pathFile directory path where to search for files * @return set of file paths under <code>pathFile</code> that matches * <code>regex</code>// ww w.j a va 2 s. c om */ public static Set<String> Find(String regex, String pathFile) { Set<String> regexfinal = new HashSet<String>(); String[] tab; File file = null; //open a file try { file = new File(pathFile); } catch (NullPointerException npe) { npe.printStackTrace(Err.getPrintWriter()); } Pattern pattern = Pattern.compile("^" + regex); if (file.isDirectory()) { tab = file.list(); for (int i = 0; i <= tab.length - 1; i++) { String finalPath = pathFile + "/" + tab[i]; Matcher matcher = pattern.matcher(finalPath); if (matcher.matches()) { regexfinal.add(finalPath); } } } else { if (file.isFile()) { Matcher matcher = pattern.matcher(pathFile); if (matcher.matches()) { regexfinal.add(pathFile); } } } return regexfinal; }
From source file:net.sf.joost.trax.TemplatesImpl.java
/** * Configures the <code>Templates</code> - initializing by parsing the * stylesheet.//from www . j a va 2 s . c om * @param reader The <code>XMLReader</code> for parsing the stylesheet * @param isource The <code>InputSource</code> of the stylesheet * @throws TransformerConfigurationException When an error occurs while * initializing the <code>Templates</code>. */ private void init(XMLReader reader, InputSource isource) throws TransformerConfigurationException { if (DEBUG) log.debug("init with InputSource " + isource.getSystemId()); try { /** * Register ErrorListener from * {@link TransformerFactoryImpl#getErrorListener()} * if available. */ // check if transformerfactory is in debug mode boolean debugmode = ((Boolean) this.factory.getAttribute(DEBUG_FEATURE)).booleanValue(); ParseContext pContext = new ParseContext(); pContext.allowExternalFunctions = factory.allowExternalFunctions; pContext.setErrorListener(factory.getErrorListener()); pContext.uriResolver = factory.getURIResolver(); if (debugmode) { if (DEBUG) log.info("init transformer in debug mode"); pContext.parserListener = factory.getParserListenerMgr(); processor = new DebugProcessor(reader, isource, pContext, factory.getMessageEmitter()); } else { processor = new Processor(reader, isource, pContext); } processor.setTransformerHandlerResolver(factory.thResolver); processor.setOutputURIResolver(factory.outputUriResolver); } catch (java.io.IOException iE) { if (DEBUG) log.debug(iE); throw new TransformerConfigurationException(iE.getMessage(), iE); } catch (org.xml.sax.SAXException sE) { Exception emb = sE.getException(); if (emb instanceof TransformerConfigurationException) throw (TransformerConfigurationException) emb; if (DEBUG) log.debug(sE); throw new TransformerConfigurationException(sE.getMessage(), sE); } catch (java.lang.NullPointerException nE) { if (DEBUG) log.debug(nE); nE.printStackTrace(System.err); throw new TransformerConfigurationException( "could not found value for property javax.xml.parsers.SAXParser ", nE); } }
From source file:org.hexlogic.model.DockerNode.java
@VsoMethod(showInApi = true, name = "pullImage", description = "Pull the image matching the given string from the docker hub repository, saving it on the docker host.") public String pullImage(String imageName) throws Exception { log.debug("Pulling image '" + imageName + "'..."); @SuppressWarnings("rawtypes") MappingIterator<Map> it = null; try {// ww w . j a v a2s .c om configureNode(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); log.debug("Starting pull operation..."); /* * We will check the final result by comparing the initial image id, which is the first ID provided by the stream such as: * * {status=Pulling image (latest) from dockerfile/nodejs, progressDetail={}, id=406eb4a4dcad} * * to the image id of the last entity which owns id AND status which will look something like: * {status=Download complete, progressDetail={}, id=406eb4a4dcad} * * If both IDs match, we know that the latest layer is the same as the requested image layer. * So the next step is to compare the download status of that layer */ String firstId = null; String lastId = ""; String lastStatus = "undefined"; /* * In addition to the download status of the layer, we provide additional information about how the process went by * returning information to the user using the last entity which has no id and only a status, which looks like this: * {status=Status: Image is up to date for dockerfile/nodejs} * or * {status=Status: Downloaded newer image for dockerfile/nodejs} * or * {status=Repository dockerfile/nodejs already being pulled by another client. Waiting.} */ String finalStatus = "undefined"; for (it = new ObjectMapper().readValues( new JsonFactory().createJsonParser(dockerClient.pullImageCmd(imageName).exec()), Map.class); it .hasNext();) { Map<?, ?> element = it.next(); String id = ""; String status = ""; String progress = ""; // info OUTPUT // log.debug("info: " + element); try { id = element.get("id").toString(); } catch (NullPointerException e) {/* catch exception if key was not found */ } try { status = element.get("status").toString(); } catch (NullPointerException e) {/* catch exception if key was not found */ } try { progress = element.get("progress").toString(); } catch (NullPointerException e) {/* catch exception if key was not found */ } // if the key was found and we got some status if (!id.isEmpty() && !status.isEmpty()) { // remember the first id of the output stream, which is the id of the image we want to pull if (firstId == null) { log.debug("Remembering first id: " + id); firstId = id; } // if the same layer is returned multiple times in a row, don't log everything but just the progress if (id.equals(lastId)) { lastId = id; lastStatus = status; if (!progress.isEmpty()) { log.debug("Progress: " + progress); } } else { lastId = id; log.debug("Image '" + id + "' status is: " + status + "."); if (!progress.isEmpty()) { log.debug("Progress: " + progress); } } } if (!status.isEmpty()) { finalStatus = status; } } // TODO find a more robust way to handle downloadStatus and finalStatus String downloadStatus = "undefined"; if (lastId.equals(firstId)) { log.debug("Last download layer id does match the requested image id: " + firstId); if (StringUtils.containsIgnoreCase(lastStatus, "Download complete")) { downloadStatus = "successed"; log.debug("The requested layer was downloaded successfuly."); } else { downloadStatus = "failed"; log.error("The requested layer failed to download."); // throw exception in order for the workflow to fail throw new IllegalStateException("The requested layer failed to download."); } } // reload images from docker node this.reloadImages(); // update inventory - another way to do this would be to update our ArrayList and call notifyElementDeleted on the image object notificationHandler.notifyElementInvalidate(toRef()); log.debug("Pull operation " + downloadStatus + ". " + finalStatus + "."); return "Pull operation " + downloadStatus + ". " + finalStatus + "."; } catch (InternalServerErrorException e) { // image dosn't exist log.error("Error: the image was not found."); // Throw error detail message so vCO can display it throw new Exception("Error: the image was not found."); } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error while pulling image: " + sw.getBuffer().toString()); // Throw error detail message so vCO can display it throw new Exception("Error while pulling image: " + sw.getBuffer().toString()); } finally { if (it != null) { log.debug("Closeing pullImage stream..."); it.close(); log.debug("Closed pullImage stream."); } } }
From source file:org.kontalk.xmppserver.KontalkIqRegister.java
@Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (log.isLoggable(Level.FINEST)) { log.finest("Processing packet: " + packet.toString()); }/* w ww .j av a2 s . com*/ if (session == null) { if (log.isLoggable(Level.FINEST)) { log.finest("Session is null, ignoring"); } return; } BareJID id = session.getDomainAsJID().getBareJID(); if (packet.getStanzaTo() != null) { id = packet.getStanzaTo().getBareJID(); } try { if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId()) && (!session.isAuthorized() || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) { Element request = packet.getElement(); if (!session.isAuthorized()) { if (!session.getDomain().isRegisterEnabled()) { results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet, "Registration is not allowed for this domain.", true)); ++statsInvalidRegistrations; return; } } StanzaType type = packet.getType(); switch (type) { case set: { // FIXME handle all the cases according to the FORM_TYPE Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]); Element formElement = (query != null) ? query.getChild(IQ_FORM_ELEM_NAME, IQ_FORM_XMLNS) : null; if (formElement != null) { Form form = new Form(formElement); // phone number: verification code String phone = form.getAsString(FORM_FIELD_PHONE); if (!session.isAuthorized() && phone != null) { boolean force; try { force = form.getAsBoolean(FORM_FIELD_FORCE); } catch (NullPointerException e) { force = false; } boolean fallback; try { fallback = form.getAsBoolean(FORM_FIELD_FALLBACK); } catch (NullPointerException e) { fallback = false; } String challenge; try { challenge = form.getAsString(FORM_FIELD_CHALLENGE); } catch (NullPointerException e) { challenge = null; } Packet response = registerPhone(session, packet, phone, force, fallback, challenge, results); statsRegistrationAttempts++; packet.processedBy(ID); if (response != null) results.offer(response); break; } // verification code: key submission String code = form.getAsString(FORM_FIELD_CODE); // get public key block from client certificate byte[] publicKeyData = getPublicKey(session); if (!session.isAuthorized()) { // load public key PGPPublicKey key = loadPublicKey(publicKeyData); // verify user id BareJID jid = verifyPublicKey(session, key); if (verifyCode(session, jid, code)) { byte[] signedKey = signPublicKey(session, publicKeyData); Packet response = register(session, packet, jid, key.getFingerprint(), signedKey); statsRegisteredUsers++; packet.processedBy(ID); results.offer(response); } else { // invalid verification code results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_INVALID_CODE, true)); } // clear throttling clearThrottling(jid, session.getConnectionId()); break; } if (session.isAuthorized()) { // private key storage String privateKey = form.getAsString(FORM_FIELD_PRIVATEKEY); if (privateKey != null) { Packet response = storePrivateKey(session, repo, packet, privateKey); packet.processedBy(ID); results.offer(response); break; } else { // public key + revoked key: key rollover or upgrade from legacy String oldFingerprint; try { oldFingerprint = KontalkAuth.getUserFingerprint(session); } catch (UserNotFoundException e) { oldFingerprint = null; log.log(Level.INFO, "user not found: {0}", session); } if (oldFingerprint != null) { // do not use public key from certificate publicKeyData = null; // user already has a key, check if revoked key fingerprint matches String publicKey = form.getAsString(FORM_FIELD_PUBLICKEY); String revoked = form.getAsString(FORM_FIELD_REVOKED); if (publicKey != null && revoked != null) { publicKeyData = Base64.decode(publicKey); byte[] revokedData = Base64.decode(revoked); KontalkKeyring keyring = getKeyring(session); if (!keyring.revoked(revokedData, oldFingerprint)) { // invalid revocation key log.log(Level.INFO, "Invalid revocation key for user {0}", session.getBareJID()); results.offer(Authorization.FORBIDDEN.getResponseMessage(packet, ERROR_INVALID_REVOKED, false)); break; } } } // user has no key or revocation key was fine, accept the new key if (publicKeyData != null) { rolloverContinue(session, publicKeyData, packet, results); break; } } } } // bad request results.offer( Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_MALFORMED_REQUEST, true)); break; } case get: { Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]); Element account = query.getChild(IQ_ACCOUNT_ELEM_NAME, IQ_ACCOUNT_XMLNS); if (account != null) { String token = account.getChildCData(new String[] { IQ_ACCOUNT_ELEM_NAME, IQ_ACCOUNT_PRIVATEKEY_ELEM_NAME, IQ_ACCOUNT_TOKEN_ELEM_NAME }); if (StringUtils.isNotEmpty(token)) { Packet response = retrievePrivateKey(session, repo, packet, token); response.processedBy(ID); results.offer(response); break; } } // instructions form results.offer(buildInstructionsForm(packet)); break; } default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true)); break; } } else { if (session.isUserId(id)) { // It might be a registration request from transport for // example... Packet pack_res = packet.copyElementOnly(); pack_res.setPacketTo(session.getConnectionId()); results.offer(pack_res); } else { results.offer(packet.copyElementOnly()); } } } catch (NotAuthorizedException e) { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized to change registration settings.\n" + e.getMessage(), true)); } catch (TigaseDBException e) { log.warning("Database problem: " + e); results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet, "Database access problem, please contact administrator.", true)); } // generated from PGP catch (IOException e) { log.warning("Unknown error: " + e); results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet, "Internal PGP error. Please contact administrator.", true)); } catch (PGPException e) { e.printStackTrace(System.err); log.warning("PGP problem: " + e); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_INVALID_PUBKEY, true)); } }