List of usage examples for java.net URLConnection getContent
public Object getContent() throws IOException
From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildScanDescriptor.java
/** * Performs on-the-fly validation of the form field 'serverUrl'. * *///from w w w . ja v a2 s . co m public FormValidation doCheckServerUrl(@QueryParameter("serverUrl") final String serverUrl) throws IOException, ServletException { if (StringUtils.isBlank(serverUrl)) { return FormValidation.error(Messages.HubBuildScan_getPleaseSetServerUrl()); } URL url; try { url = new URL(serverUrl); try { url.toURI(); } catch (final URISyntaxException e) { return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl()); } } catch (final MalformedURLException e) { return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl()); } try { Proxy proxy = null; final Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { final ProxyConfiguration proxyConfig = jenkins.proxy; if (proxyConfig != null) { proxy = ProxyConfiguration.createProxy(url.getHost(), proxyConfig.name, proxyConfig.port, proxyConfig.noProxyHost); if (proxy != null && proxy != Proxy.NO_PROXY) { if (StringUtils.isNotBlank(proxyConfig.getUserName()) && StringUtils.isNotBlank(proxyConfig.getPassword())) { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyConfig.getUserName(), proxyConfig.getPassword().toCharArray()); } }); } else { Authenticator.setDefault(null); } } } } URLConnection connection = null; if (proxy != null) { connection = url.openConnection(proxy); } else { connection = url.openConnection(); } connection.getContent(); } catch (final IOException ioe) { return FormValidation.error(ioe, Messages.HubBuildScan_getCanNotReachThisServer_0_(serverUrl)); } catch (final RuntimeException e) { return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl()); } return FormValidation.ok(); }
From source file:io.fabric8.apiman.rest.Kubernetes2ApimanFilter.java
/** * Checks of the descriptionDocument can be obtained from the service. If the * service is still deploying we will hold off and return false. * * @param bean/*from w w w . j av a2 s . c o m*/ * @return true of the desciptionDocument is ready to be read. */ private boolean isServiceReady(AvailableApiBean bean) { log.debug("DefinitionType: " + bean.getDefinitionType()); URL defUrl = null; if (bean.getDefinitionType() != null && !"None".equals(bean.getDefinitionType().name())) { try { defUrl = new URL(bean.getDefinitionUrl()); URLConnection urlConnection = defUrl.openConnection(); log.info("Trying to obtain descriptionDoc for service " + bean.getName()); urlConnection.setConnectTimeout(250); if (urlConnection.getContentLength() > 0) { log.debug("DefinitionDoc at 'Ready to be read " + urlConnection.getContent()); return true; } else { //try the route defUrl = new URL(bean.getRouteDefinitionUrl()); urlConnection = defUrl.openConnection(); log.info("Trying to obtain descriptionDoc for service " + bean.getName()); urlConnection.setConnectTimeout(250); if (urlConnection.getContentLength() > 0) { bean.setDefinitionUrl(defUrl.toExternalForm()); return true; } else { log.info("DefinitionDoc for '" + bean.getName() + "' not ready to be read from " + defUrl.toExternalForm()); } return false; } } catch (Exception e) { log.info("DefinitionDoc for '" + bean.getName() + "' can't be read. " + e.getMessage()); return false; } } return true; }
From source file:com.blackducksoftware.integration.hub.builder.HubServerConfigBuilder.java
public void validateHubUrl(final ValidationResults<GlobalFieldKey, HubServerConfig> result) { assertProxyValid();/*from w w w . j av a2s .c om*/ if (hubUrl == null) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_FOUND)); return; } URL hubURL = null; try { hubURL = new URL(hubUrl); hubURL.toURI(); } catch (final MalformedURLException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID)); } catch (final URISyntaxException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID)); } if (hubURL == null) { return; } try { URLConnection connection = null; if (proxyInfo != null) { if (!hubURL.getProtocol().equals("https") && proxyInfo.getUsername() != null && proxyInfo.getEncryptedPassword() != null) { result.addResult(HubProxyInfoFieldEnum.PROXYUSERNAME, new ValidationResult( ValidationResultEnum.ERROR, ERROR_MSG_AUTHENTICATED_PROXY_WITH_HTTPS)); return; } connection = proxyInfo.openConnection(hubURL); } else { connection = hubURL.openConnection(); } final int timeoutIntMillisec = 1000 * stringToNonNegativeInteger(timeoutSeconds); connection.setConnectTimeout(timeoutIntMillisec); connection.setReadTimeout(timeoutIntMillisec); connection.getContent(); } catch (final IOException ioe) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_UNREACHABLE_PREFIX + hubUrl, ioe)); return; } catch (final RuntimeException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID_PREFIX + hubUrl, e)); return; } result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.OK, "")); }
From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java
/** * Send activation request if subscribed to the activated URI * * @param subscriber/*from w w w . jav a2 s . c o m*/ * @param activationContent * @throws ExchangeException */ private synchronized void activate(Subscriber subscriber, ActivationContent activationContent) throws ExchangeException { if (!isSubscribed(subscriber)) { if (log.isDebugEnabled()) { log.debug("Exchange : subscriber [{}] is not subscribed to {}", subscriber.getName(), this.path); } return; } if (log.isDebugEnabled()) { log.debug("Exchange : sending activation request to {}", subscriber.getName()); //$NON-NLS-1$ log.debug("Exchange : user [{}]", this.user.getName()); //$NON-NLS-1$ } String handle = getActivationURL(subscriber); try { URL url = new URL(handle); URLConnection urlConnection = url.openConnection(); this.addActivationHeaders(urlConnection, activationContent); Transporter.transport(urlConnection, activationContent); String status = urlConnection.getHeaderField(SimpleSyndicator.ACTIVATION_ATTRIBUTE_STATUS); // check if the activation failed if (StringUtils.equals(status, SimpleSyndicator.ACTIVATION_FAILED)) { String message = urlConnection.getHeaderField(SimpleSyndicator.ACTIVATION_ATTRIBUTE_MESSAGE); throw new ExchangeException("Message received from subscriber: " + message); } urlConnection.getContent(); log.info("Exchange : activation request received by {}", subscriber.getName()); //$NON-NLS-1$ } catch (ExchangeException e) { throw e; } catch (MalformedURLException e) { throw new ExchangeException("Incorrect URL for subscriber " + subscriber + "[" + handle + "]"); } catch (IOException e) { throw new ExchangeException( "Not able to send the activation request [" + handle + "]: " + e.getMessage()); } catch (Exception e) { throw new ExchangeException(e); } }
From source file:org.apache.openjpa.meta.AbstractCFMetaDataFactory.java
/** * Parse persistent type names.//ww w. j ava2 s.c o m */ protected Set<String> parsePersistentTypeNames(ClassLoader loader) throws IOException { ClassArgParser cparser = newClassArgParser(); String[] clss; Set<String> names = new HashSet<String>(); if (files != null) { File file; for (Iterator itr = files.iterator(); itr.hasNext();) { file = (File) itr.next(); if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file))).booleanValue()) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-directory", file)); scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file); } else if (file.getName().endsWith(".jar")) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar", file)); try { ZipFile zFile = AccessController.doPrivileged(J2DoPrivHelper.newZipFileAction(file)); scan(new ZipFileMetaDataIterator(zFile, newMetaDataFilter()), cparser, names, true, file); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } } else { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-file", file)); clss = cparser.parseTypeNames(new FileMetaDataIterator(file)); List<String> newNames = Arrays.asList(clss); if (log.isTraceEnabled()) log.trace(_loc.get("scan-found-names", newNames, file)); names.addAll(newNames); File f = AccessController.doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(file)); try { mapPersistentTypeNames(AccessController.doPrivileged(J2DoPrivHelper.toURLAction(f)), clss); } catch (PrivilegedActionException pae) { throw (FileNotFoundException) pae.getException(); } } } } URL url; if (urls != null) { for (Iterator itr = urls.iterator(); itr.hasNext();) { url = (URL) itr.next(); if ("file".equals(url.getProtocol())) { File file = AccessController .doPrivileged(J2DoPrivHelper.getAbsoluteFileAction(new File(url.getFile()))); if (files != null && files.contains(file)) { continue; } else if ((AccessController.doPrivileged(J2DoPrivHelper.isDirectoryAction(file))) .booleanValue()) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-directory", file)); scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file); continue; } } if ("vfs".equals(url.getProtocol())) { if (log.isTraceEnabled()) { log.trace(_loc.get("scanning-vfs-url", url)); } final URLConnection conn = url.openConnection(); final Object vfsContent = conn.getContent(); final URL finalUrl = url; File file = AccessController.doPrivileged(new PrivilegedAction<File>() { @SuppressWarnings({ "rawtypes", "unchecked" }) public File run() { try { Class virtualFileClass = Class.forName("org.jboss.vfs.VirtualFile"); Method getPhysicalFile = virtualFileClass.getDeclaredMethod("getPhysicalFile"); return (File) getPhysicalFile.invoke(vfsContent); } catch (Exception e) { log.error(_loc.get("while-scanning-vfs-url", finalUrl), e); } return null; } }); if (file != null) scan(new FileMetaDataIterator(file, newMetaDataFilter()), cparser, names, true, file); continue; } if ("jar".equals(url.getProtocol())) { if (url.getPath().endsWith("!/")) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar-url", url)); scan(new ZipFileMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url); } else { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar-url", url)); scan(new JarFileURLMetaDataIterator(url, newMetaDataFilter()), cparser, names, true, url); } } else if (url.getPath().endsWith(".jar")) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar-at-url", url)); try { InputStream is = (InputStream) AccessController .doPrivileged(J2DoPrivHelper.openStreamAction(url)); scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser, names, true, url); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } } else { // Open an InputStream from the URL and sniff for a zip header. If it is, then this is // a URL with a jar-formated InputStream, as per the JPA specification. Otherwise, fall back // to URLMetaDataIterator. BufferedInputStream is = null; try { is = new BufferedInputStream( (InputStream) AccessController.doPrivileged(J2DoPrivHelper.openStreamAction(url))); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } // Check for zip header magic 0x50 0x4b 0x03 0x04 is.mark(0); boolean zipHeaderMatch = is.read() == 0x50 && is.read() == 0x4b && is.read() == 0x03 && is.read() == 0x04; is.reset(); if (zipHeaderMatch) { // The URL provides a Jar-formatted InputStream, consume it with ZipStreamMetaDataIterator if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar-at-url", url)); scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser, names, true, url); } else { // Fall back to URLMetaDataIterator if (log.isTraceEnabled()) log.trace(_loc.get("scanning-url", url)); clss = cparser.parseTypeNames(new URLMetaDataIterator(url)); List<String> newNames = Arrays.asList(clss); if (log.isTraceEnabled()) log.trace(_loc.get("scan-found-names", newNames, url)); names.addAll(newNames); mapPersistentTypeNames(url, clss); } } } } if (rsrcs != null) { String rsrc; MetaDataIterator mitr; for (Iterator itr = rsrcs.iterator(); itr.hasNext();) { rsrc = (String) itr.next(); if (rsrc.endsWith(".jar")) { url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc)); if (url != null) { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-jar-stream-url", url)); try { InputStream is = (InputStream) AccessController .doPrivileged(J2DoPrivHelper.openStreamAction(url)); scan(new ZipStreamMetaDataIterator(new ZipInputStream(is), newMetaDataFilter()), cparser, names, true, url); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } } } else { if (log.isTraceEnabled()) log.trace(_loc.get("scanning-resource", rsrc)); mitr = new ResourceMetaDataIterator(rsrc, loader); OpenJPAConfiguration conf = repos.getConfiguration(); Map peMap = null; if (conf instanceof OpenJPAConfigurationImpl) peMap = ((OpenJPAConfigurationImpl) conf).getPersistenceEnvironment(); URL puUrl = peMap == null ? null : (URL) peMap.get(PERSISTENCE_UNIT_ROOT_URL); List<String> mappingFileNames = peMap == null ? null : (List<String>) peMap.get(MAPPING_FILE_NAMES); List<URL> jars = peMap == null ? null : (List<URL>) peMap.get(JAR_FILE_URLS); String puUrlString = puUrl == null ? null : puUrl.toString(); if (log.isTraceEnabled()) log.trace(_loc.get("pu-root-url", puUrlString)); URL puORMUrl = null; try { if (puUrlString != null) { String puORMUrlStr = puUrlString + (puUrlString.endsWith("/") ? "" : "/") + rsrc; puORMUrl = AccessController.doPrivileged(J2DoPrivHelper.createURL(puORMUrlStr)); } } catch (PrivilegedActionException e) { throw new IOException("Error generating puORMUrlStr.", e.getCause()); } List<URL> urls = new ArrayList<URL>(3); while (mitr.hasNext()) { url = (URL) mitr.next(); String urlString = url.toString(); if (log.isTraceEnabled()) log.trace(_loc.get("resource-url", urlString)); if (peMap != null) { //OPENJPA-2102: decode the URL to remove such things a spaces (' ') encoded as '%20' if (puUrlString != null && decode(urlString).indexOf(decode(puUrlString)) != -1) { urls.add(url); } else if (puORMUrl != null && puORMUrl.equals(url)) { // Check URL equality to support encapsulating URL protocols urls.add(url); } if (mappingFileNames != null && mappingFileNames.size() != 0) { for (String mappingFileName : mappingFileNames) { if (log.isTraceEnabled()) log.trace(_loc.get("mapping-file-name", mappingFileName)); if (urlString.indexOf(mappingFileName) != -1) urls.add(url); } } if (jars != null && jars.size() != 0) { for (URL jarUrl : jars) { if (log.isTraceEnabled()) log.trace(_loc.get("jar-file-url", jarUrl)); if (urlString.indexOf(jarUrl.toString()) != -1) urls.add(url); } } } else { urls.add(url); } } mitr.close(); for (Object obj : urls) { url = (URL) obj; clss = cparser.parseTypeNames(new URLMetaDataIterator(url)); List<String> newNames = Arrays.asList(clss); if (log.isTraceEnabled()) log.trace(_loc.get("scan-found-names", newNames, rsrc)); names.addAll(newNames); mapPersistentTypeNames(url, clss); } } } } if (cpath != null) { String[] dirs = (String[]) cpath.toArray(new String[cpath.size()]); scan(new ClasspathMetaDataIterator(dirs, newMetaDataFilter()), cparser, names, true, dirs); } if (types != null) names.addAll(types); if (log.isTraceEnabled()) log.trace(_loc.get("parse-found-names", names)); return names; }
From source file:er.extensions.appserver.ERXApplication.java
/** * <p>Terminates a different instance of the same application that may already be running.<br> * Only in dev mode.</p>/*from w w w . j av a 2 s .co m*/ * <p>Set the property "er.extensions.ERXApplication.allowMultipleDevInstances" to "true" if * you need to run multiple instances in dev mode.</p> * * @return true if a previously running instance was stopped. */ private static boolean stopPreviousDevInstance() { if (!isDevelopmentModeSafe() || ERXProperties .booleanForKeyWithDefault("er.extensions.ERXApplication.allowMultipleDevInstances", false)) { return false; } if (!(application().wasMainInvoked())) { return false; } String adapterUrl; if (application().host() != null) { adapterUrl = application().cgiAdaptorURL(); } else { adapterUrl = application().cgiAdaptorURL().replace("://null/", "://localhost/"); } String appUrl; if (application().isDirectConnectEnabled()) { appUrl = adapterUrl.replace("/cgi", ":" + application().port() + "/cgi"); appUrl += "/" + application().name() + application().applicationExtension(); } else { appUrl = adapterUrl + "/" + application().name() + application().applicationExtension() + "/-" + application().port(); } URL url; try { appUrl = appUrl + "/" + application().directActionRequestHandlerKey() + "/stop"; url = new URL(appUrl); log.debug("Stopping previously running instance of " + application().name()); URLConnection connection = url.openConnection(); connection.getContent(); Thread.sleep(2000); return true; } catch (Throwable e) { e.printStackTrace(); } return false; }