List of usage examples for java.net Authenticator setDefault
public static synchronized void setDefault(Authenticator a)
From source file:org.talend.core.nexus.NexusServerUtils.java
public static String resolveSha1(String nexusUrl, final String userName, final String password, String repositoryId, String groupId, String artifactId, String version, String type) throws Exception { HttpURLConnection urlConnection = null; final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator(); if (userName != null && !"".equals(userName)) { Authenticator.setDefault(new Authenticator() { @Override/*from w ww . j a v a2 s . c om*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } try { String service = NexusConstants.SERVICES_RESOLVE + "a=" + artifactId + "&g=" + groupId + "&r=" + repositoryId + "&v=" + version + "&p=" + type; urlConnection = getHttpURLConnection(nexusUrl, service, userName, password); SAXReader saxReader = new SAXReader(); InputStream inputStream = urlConnection.getInputStream(); Document document = saxReader.read(inputStream); Node sha1Node = document.selectSingleNode("/artifact-resolution/data/sha1"); String sha1 = null; if (sha1Node != null) { sha1 = sha1Node.getText(); } return sha1; } catch (FileNotFoundException e) { // jar not existing on remote nexus return null; } finally { Authenticator.setDefault(defaultAuthenticator); if (null != urlConnection) { urlConnection.disconnect(); } } }
From source file:savant.view.swing.Savant.java
/** * Creates new form Savant//from w w w .j a v a2s . co m */ private Savant(boolean isStandalone, boolean pluginsEnabled) { this.isStandalone = isStandalone; try { basicService = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService"); webStart = true; } catch (UnavailableServiceException e) { //System.err.println("Lookup failed: " + e); webStart = false; } instance = this; Splash s = new Splash(instance, false); if (isStandalone()) { s.setVisible(true); } Authenticator.setDefault(new SavantHTTPAuthenticator()); addComponentListener(new ComponentAdapter() { /** * Resize the form to the minimum size if the user has resized it to * something smaller. * * @param e The resize event */ @Override public void componentResized(ComponentEvent e) { int width = getWidth(); int height = getHeight(); //we check if either the width //or the height are below minimum boolean resize = false; if (width < minimumFormWidth) { resize = true; width = minimumFormWidth; } if (height < minimumFormHeight) { resize = true; height = minimumFormHeight; } if (resize) { setSize(width, height); } } }); GraphPaneController.getInstance().addListener(new Listener<GraphPaneEvent>() { @Override public void handleEvent(GraphPaneEvent event) { GraphPaneController controller = GraphPaneController.getInstance(); switch (event.getType()) { case HIGHLIGHTING: plumblineItem.setSelected(controller.isPlumbing()); spotlightItem.setSelected(controller.isSpotlight()); crosshairItem.setSelected(controller.isAiming()); break; case MOUSE: updateMousePosition(event.getMouseX(), event.getMouseY(), event.isYIntegral()); break; case STATUS: updateStatus(event.getStatus()); break; } } }); ProjectController.getInstance().addListener(new Listener<ProjectEvent>() { @Override public void handleEvent(ProjectEvent event) { String activity; switch (event.getType()) { case LOADING: activity = "Loading " + event.getPath() + "..."; setTitle("Savant Genome Browser - " + activity); break; case LOADED: case SAVED: MiscUtils.setUnsavedTitle(Savant.this, "Savant Genome Browser - " + event.getPath(), false); break; case SAVING: activity = "Saving " + event.getPath() + "..."; setTitle("Savant Genome Browser - " + activity); break; case UNSAVED: MiscUtils.setUnsavedTitle(Savant.this, "Savant Genome Browser - " + event.getPath(), true); break; } } }); GenomeController.getInstance().addListener(new Listener<GenomeChangedEvent>() { @Override public void handleEvent(GenomeChangedEvent event) { LOG.info("Genome changed from " + event.getOldGenome() + " to " + event.getNewGenome()); loadGenomeItem.setText("Change genome..."); showBrowserControls(); } }); s.setStatus("Initializing GUI"); initComponents(); customizeUI(); init(); initHiddenShortcuts(); if (BrowserSettings.getCheckVersionOnStartup()) { s.setStatus("Checking version"); checkVersion(false); } if (BrowserSettings.getCollectAnonymousUsage()) { logUsageStats(); } if (pluginsEnabled) { s.setStatus("Loading plugins"); PluginController pluginController = PluginController.getInstance(); pluginController.addListener(new Listener<PluginEvent>() { @Override public void handleEvent(PluginEvent event) { SavantPlugin plugin = event.getPlugin(); if (event.getType() == PluginEvent.Type.LOADED) { if (plugin instanceof SavantPanelPlugin) { DockableFrame f = DockableFrameFactory.createGUIPluginFrame(plugin.getTitle()); JPanel p = (JPanel) f.getContentPane(); p.setLayout(new BorderLayout()); p.add(event.getCanvas(), BorderLayout.CENTER); auxDockingManager.addFrame(f); addPluginToMenu(new PluginMenuItem((SavantPanelPlugin) plugin)); } else if (event.getPlugin() instanceof SavantDataSourcePlugin) { loadFromDataSourcePluginItem.setText("Load Track from Other Datasource..."); } } } }); pluginController.loadPlugins(DirectorySettings.getPluginsDirectory()); } s.setStatus("Organizing layout"); displayBookmarksPanel(); if (turnExperimentalFeaturesOff) { disableExperimentalFeatures(); } s.setVisible(false); if (isStandalone()) { makeGUIVisible(); } }
From source file:org.panlab.tgw.restclient.RepoAdapter.java
public static ResourceSpec getResourceSpec(String type) { Client c = Client.create();/*from w ww . jav a 2 s . c om*/ c.setFollowRedirects(true); Authenticator.setDefault(new PwdAuthenticator()); WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceSpec/"); String resp = r.get(String.class); //System.out.println(resp); resp = addSchemaDefinition(resp); try { ListDocument lDoc = ListDocument.Factory.parse(resp); ResourceSpec[] rsArray = lDoc.getList().getResourceSpecArray(); for (int i = 0; i < rsArray.length; i++) if (rsArray[i].isSetCommonName() && rsArray[i].getCommonName().equalsIgnoreCase(type)) return rsArray[i]; } catch (XmlException ex) { ex.printStackTrace(); return null; } return null; }
From source file:org.fuin.esmp.AbstractEventStoreMojo.java
private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser, final String proxyPassword, final URL downloadUrl) throws URISyntaxException { // Add authenticator with proxyUser and proxyPassword if (proxyUser != null && proxyPassword != null) { Authenticator.setDefault(new Authenticator() { @Override// w w w .j av a 2s .c o m public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } final ProxySelector defaultProxySelector = ProxySelector.getDefault(); final URI downloadUri = downloadUrl.toURI(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(final URI uri) { if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) { return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))); } else { return defaultProxySelector.select(uri); } } @Override public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) { } }); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java
@Test() public void withAuthenticator() throws Exception { assertEquals("Unexpected calls to password provider", 0, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); // Set the authenticator to our Credential Manager-backed one that also // counts calls to itself CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager); assertEquals("Unexpected calls to authenticator", 0, authenticator.calls); Authenticator.setDefault(authenticator); // FixedPasswordProvider.setUsernamePassword(new UsernamePassword( // USERNAME, PASSWORD)); URL url = new URL("http://localhost:" + PORT + "/test.html"); httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD)); URLConnection c = url.openConnection(); c.connect();//from w ww. ja v a 2 s . c om try { c.getContent(); } catch (Exception ex) { } System.out.println(c.getHeaderField(0)); assertEquals("Did not invoke authenticator", 1, authenticator.calls); assertEquals("Did not invoke our password provider", 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0)); assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage()); assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString()); // And test Java's cache: URLConnection c2 = url.openConnection(); c2.connect(); assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0)); assertEquals("JVM invoked our authenticator again instead of caching", 1, authenticator.calls); assertEquals("Invoked our password provider again instead of caching", 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); }
From source file:com.diablominer.DiabloMiner.DiabloMiner.java
void execute(String[] args) throws Exception { threads.add(Thread.currentThread()); Options options = new Options(); options.addOption("u", "user", true, "bitcoin host username"); options.addOption("p", "pass", true, "bitcoin host password"); options.addOption("o", "host", true, "bitcoin host IP"); options.addOption("r", "port", true, "bitcoin host port"); options.addOption("l", "url", true, "bitcoin host url"); options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>"); options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds"); options.addOption("d", "debug", false, "enable debug output"); options.addOption("dt", "debugtimer", false, "run for 1 minute and quit"); options.addOption("D", "devices", true, "devices to enable, default all"); options.addOption("f", "fps", true, "target GPU execution timing"); options.addOption("na", "noarray", false, "turn GPU kernel array off"); options.addOption("v", "vectors", true, "vector size in GPU kernel"); options.addOption("w", "worksize", true, "override GPU worksize"); options.addOption("ds", "ksource", false, "output GPU kernel source and quit"); options.addOption("h", "help", false, "this help"); PosixParser parser = new PosixParser(); CommandLine line = null;// w ww. j a v a 2 s. c o m try { line = parser.parse(options, args); if (line.hasOption("help")) { throw new ParseException(""); } } catch (ParseException e) { System.out.println(e.getLocalizedMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options, "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf " + "before starting bitcoind or bitcoin --daemon"); return; } String splitUrl[] = null; String splitUser[] = null; String splitPass[] = null; String splitHost[] = null; String splitPort[] = null; if (line.hasOption("url")) splitUrl = line.getOptionValue("url").split(","); if (line.hasOption("user")) splitUser = line.getOptionValue("user").split(","); if (line.hasOption("pass")) splitPass = line.getOptionValue("pass").split(","); if (line.hasOption("host")) splitHost = line.getOptionValue("host").split(","); if (line.hasOption("port")) splitPort = line.getOptionValue("port").split(","); int networkStatesCount = 0; if (splitUrl != null) networkStatesCount = splitUrl.length; if (splitUser != null) networkStatesCount = Math.max(splitUser.length, networkStatesCount); if (splitPass != null) networkStatesCount = Math.max(splitPass.length, networkStatesCount); if (splitHost != null) networkStatesCount = Math.max(splitHost.length, networkStatesCount); if (splitPort != null) networkStatesCount = Math.max(splitPort.length, networkStatesCount); if (networkStatesCount == 0) { error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r"); System.exit(-1); } int j = 0; for (int i = 0; j < networkStatesCount; i++, j++) { String protocol = "http"; String host = "localhost"; int port = 8332; String path = "/"; String user = "diablominer"; String pass = "diablominer"; byte hostChain = 0; if (splitUrl != null && splitUrl.length > i) { String[] usernameFix = splitUrl[i].split("@", 3); if (usernameFix.length > 2) splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2]; URL url = new URL(splitUrl[i]); if (url.getProtocol() != null && url.getProtocol().length() > 1) protocol = url.getProtocol(); if (url.getHost() != null && url.getHost().length() > 1) host = url.getHost(); if (url.getPort() != -1) port = url.getPort(); if (url.getPath() != null && url.getPath().length() > 1) path = url.getPath(); if (url.getUserInfo() != null && url.getUserInfo().length() > 1) { String[] userPassSplit = url.getUserInfo().split(":"); user = userPassSplit[0].replace("+++++", "@"); if (userPassSplit.length > 1 && userPassSplit[1].length() > 1) pass = userPassSplit[1]; } } if (splitUser != null && splitUser.length > i) user = splitUser[i]; if (splitPass != null && splitPass.length > i) pass = splitPass[i]; if (splitHost != null && splitHost.length > i) host = splitHost[i]; if (splitPort != null && splitPort.length > i) port = Integer.parseInt(splitPort[i]); NetworkState networkState; try { networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass, hostChain); } catch (MalformedURLException e) { throw new DiabloMinerFatalException(this, "Malformed connection paramaters"); } if (networkStateHead == null) { networkStateHead = networkStateTail = networkState; } else { networkStateTail.setNetworkStateNext(networkState); networkStateTail = networkState; } } networkStateTail.setNetworkStateNext(networkStateHead); if (line.hasOption("proxy")) { final String[] proxySettings = line.getOptionValue("proxy").split(":"); if (proxySettings.length >= 2) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1]))); } if (proxySettings.length >= 3) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray()); } }); } } if (line.hasOption("worklifetime")) workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000; if (line.hasOption("debug")) debug = true; if (line.hasOption("debugtimer")) { debugtimer = true; } if (line.hasOption("devices")) { String devices[] = line.getOptionValue("devices").split(","); enabledDevices = new HashSet<String>(); for (String s : devices) { enabledDevices.add(s); if (Integer.parseInt(s) == 0) { error("Do not use 0 with -D, devices start at 1"); System.exit(-1); } } } if (line.hasOption("fps")) { GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps")); if (GPUTargetFPS < 0.1) { error("--fps argument is too low, adjusting to 0.1"); GPUTargetFPS = 0.1; } } if (line.hasOption("noarray")) { GPUNoArray = true; } if (line.hasOption("worksize")) GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize")); if (line.hasOption("vectors")) { String tempVectors[] = line.getOptionValue("vectors").split(","); GPUVectors = new Integer[tempVectors.length]; try { for (int i = 0; i < GPUVectors.length; i++) { GPUVectors[i] = Integer.parseInt(tempVectors[i]); if (GPUVectors[i] > 16) { error("DiabloMiner now uses comma-seperated vector layouts, use those instead"); System.exit(-1); } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4 && GPUVectors[i] != 8 && GPUVectors[i] != 16) { error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16"); System.exit(-1); } } Arrays.sort(GPUVectors, Collections.reverseOrder()); } catch (NumberFormatException e) { error("Cannot parse --vector argument(s)"); System.exit(-1); } } else { GPUVectors = new Integer[1]; GPUVectors[0] = 1; } if (line.hasOption("ds")) GPUDebugSource = true; info("Started"); StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString()); NetworkState networkState = networkStateHead.getNetworkStateNext(); while (networkState != networkStateHead) { list.append(", " + networkState.getQueryUrl()); networkState = networkState.getNetworkStateNext(); } info("Connecting to: " + list); long previousHashCount = 0; double previousAdjustedHashCount = 0.0; long previousAdjustedStartTime = startTime = (now()) - 1; StringBuilder hashMeter = new StringBuilder(80); Formatter hashMeterFormatter = new Formatter(hashMeter); int deviceCount = 0; List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>(); List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates(); deviceCount += GPUDeviceStates.size(); allDeviceStates.add(GPUDeviceStates); while (running.get()) { for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { deviceState.checkDevice(); } } long now = now(); long currentHashCount = hashCount.get(); double adjustedHashCount = (double) (currentHashCount - previousHashCount) / (double) (now - previousAdjustedStartTime); double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0; if (now - startTime > TIME_OFFSET * 2) { double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0; hashMeter.setLength(0); if (!debug) { hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); } else { hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); double basisAverage = 0.0; for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { hashMeterFormatter.format("%.1f ", deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0); basisAverage += deviceState.getBasis(); } } basisAverage = 1000 / (basisAverage / deviceCount); hashMeterFormatter.format("| fps: %.1f", basisAverage); } System.out.print(hashMeter); } else { System.out.print("\rWaiting..."); } if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) { previousHashCount = currentHashCount; previousAdjustedHashCount = adjustedHashCount; previousAdjustedStartTime = now - 1; } if (debugtimer && now() > startTime + 60 * 1000) { System.out.print("\n"); info("Debug timer is up, quitting..."); System.exit(0); } try { if (now - startTime > TIME_OFFSET) Thread.sleep(1000); else Thread.sleep(1); } catch (InterruptedException e) { } } hashMeterFormatter.close(); }
From source file:org.wso2.iot.agent.services.FileDownloadService.java
private void checkHTTPAuthentication(String userName, String password) { if (!userName.isEmpty()) { HTTPAuthenticator.setPasswordAuthentication(userName, password); Authenticator.setDefault(new HTTPAuthenticator()); }// w w w . j a v a 2 s . co m }
From source file:com.expressui.core.util.ApplicationProperties.java
/** * Lifecycle method called after bean is constructed. Sets http.proxyHost and http.proxyPort system property * and sets a proxy authenticator if httpProxyUsername and httpProxyPassword are not empty. *///from w w w.ja v a2s . co m @PostConstruct public void postConstruct() { if (!StringUtil.isEmpty(httpProxyHost)) { System.setProperty("http.proxyHost", httpProxyHost); } if (!StringUtil.isEmpty(httpProxyPort)) { System.setProperty("http.proxyPort", httpProxyPort.toString()); } if (!StringUtil.isEmpty(httpProxyUsername) && !StringUtil.isEmpty(httpProxyPassword)) { Authenticator.setDefault(new ProxyAuthenticator(httpProxyUsername, httpProxyPassword)); } }
From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java
/** * Constructs and executes a SOAP message. For {@code basic} authentication, YADA uses the * java soap api, and the {@link SOAPConnection} object stored in the query object. For * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC} * in {@link #YADA_BIN}. //from w w w. j a v a2 s .c o m * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery) */ @Override public void execute(YADAQuery yq) throws YADAAdaptorExecutionException { String result = ""; resetCountParameter(yq); SOAPConnection connection = (SOAPConnection) yq.getConnection(); for (int row = 0; row < yq.getData().size(); row++) { yq.setResult(); YADAQueryResult yqr = yq.getResult(); String soapUrl = yq.getSoap(row); try { this.endpoint = new URL(soapUrl); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes()); // Assume a SOAP message was built previously MimeHeaders mimeHeaders = message.getMimeHeaders(); if ("basic".equals(this.soapAuth.toLowerCase())) { mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken)); mimeHeaders.addHeader("SOAPAction", this.soapAction); mimeHeaders.addHeader("Content-Type", "text/xml"); SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody(); header.detachNode(); l.debug("query:\n" + this.queryString); try { Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(this.soapData.getBytes())); //SOAPBodyElement docElement = body.addDocument(xml); Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass)); SOAPMessage response = connection.call(message, this.endpoint); try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) { response.writeTo(responseOutputStream); result = responseOutputStream.toString(); } } catch (IOException e) { String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue."; throw new YADAAdaptorExecutionException(msg, e); } l.debug("SOAP Body:\n" + result); } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase()) || "negotiate".equals(this.soapAuth.toLowerCase())) { ArrayList<String> args = new ArrayList<>(); args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC); args.add("-X"); args.add("-s"); args.add(this.soapSource + this.soapPath); args.add("-u"); args.add(this.soapDomain + "\\" + this.soapUser); args.add("-p"); args.add(this.soapPass); args.add("-a"); args.add(this.soapAuth); args.add("-q"); args.add(this.soapData); args.add("-t"); args.add(this.soapAction); String[] cmds = args.toArray(new String[0]); l.debug("Executing soap request via script: " + Arrays.toString(cmds)); String s = null; try { ProcessBuilder pb = new ProcessBuilder(args); l.debug(pb.environment().toString()); pb.redirectErrorStream(true); Process p = pb.start(); try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) { while ((s = si.readLine()) != null) { l.debug(s); if (null == result) { result = ""; } result += s; } } } catch (IOException e) { String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'. Make sure the curl executable is still accessible."; throw new YADAAdaptorExecutionException(msg, e); } } } catch (SOAPException e) { String msg = "There was a problem creating or executing the SOAP message, or receiving the response."; throw new YADAAdaptorExecutionException(msg, e); } catch (SAXException e) { String msg = "Unable to parse SOAP message body."; throw new YADAAdaptorExecutionException(msg, e); } catch (ParserConfigurationException e) { String msg = "There was a problem creating the xml document for the SOAP message body."; throw new YADAAdaptorExecutionException(msg, e); } catch (YADAResourceException e) { String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC; throw new YADAAdaptorExecutionException(msg, e); } catch (MalformedURLException e) { String msg = "Can't create URL from provided source and path."; throw new YADAAdaptorExecutionException(msg, e); } finally { try { ConnectionFactory.releaseResources(connection, yq.getSoap().get(0)); } catch (YADAConnectionException e) { l.error(e.getMessage()); } } yqr.addResult(row, result); } }
From source file:org.panlab.tgw.restclient.RepoAdapter.java
public static String createAtomic(String commonName, String paramType, String defaultValue, String description) {// w w w . j a va2 s .c o m Client c = Client.create(); c.setFollowRedirects(true); Authenticator.setDefault(new PwdAuthenticator()); WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamAtomic/"); ConfigParamAtomicInstanceDocument pDoc = ConfigParamAtomicInstanceDocument.Factory.newInstance(); pDoc.addNewConfigParamAtomicInstance(); pDoc.getConfigParamAtomicInstance().setCommonName(commonName); pDoc.getConfigParamAtomicInstance().setConfigParamType(paramType); pDoc.getConfigParamAtomicInstance().setDefaultParamValue(defaultValue); pDoc.getConfigParamAtomicInstance().setDescription(description); String request = pDoc.toString(); request = request.replace(" xmlns=\"http://xml.netbeans.org/schema/repo.xsd\"", ""); request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + request; String resp = r.type(MediaType.TEXT_XML).post(String.class, request); resp = addSchemaDefinition(resp); try { ConfigParamAtomicDocument pcDoc = ConfigParamAtomicDocument.Factory.parse(resp); return pcDoc.getConfigParamAtomic().getId(); } catch (XmlException ex) { return null; } }