Introduce HttpUtils, utility handling http get and post request. One place to handle certificates, http authentication, hostname verification, site redirects.

cusax-fix
Damian Minkov 15 years ago
parent 379c9cd4e8
commit 98e008ec3a

@ -901,7 +901,7 @@
bundle-plugin-icqaccregwizz,bundle-plugin-jabberaccregwizz,
bundle-plugin-msnaccregwizz,bundle-plugin-sipaccregwizz,
bundle-plugin-yahooaccregwizz,bundle-plugin-aimaccregwizz,
bundle-httpcore,bundle-httpclient,bundle-plugin-spellcheck,
bundle-httputil,bundle-plugin-spellcheck,
bundle-version,bundle-version-impl,bundle-shutdown-timeout,
bundle-growlnotification,bundle-swingnotification,bundle-galagonotification,
bundle-sparkle, bundle-plugin-branding,
@ -2013,77 +2013,16 @@ javax.swing.event, javax.swing.border"/>
</jar>
</target>
<!--BUNDLE-HTTPCORE -->
<target name="bundle-httpcore">
<jar compress="true" destfile="${bundles.dest}/httpcore.jar"
filesetmanifest="merge">
<zipfileset src="${lib.noinst}/httpcore-4.0.1.jar" prefix=""/>
<manifest>
<attribute name="Export-Package"
value="org.apache.http,
org.apache.http.entity,
org.apache.http.impl,
org.apache.http.impl.entity,
org.apache.http.impl.io,
org.apache.http.io,
org.apache.http.message,
org.apache.http.params,
org.apache.http.protocol,
org.apache.http.util"/>
<attribute name="Import-Package"
value="org.apache.commons.logging"/>
<attribute name="Bundle-Name"
value="Apache HttpComponents Core"/>
<attribute name="Bundle-Description"
value="A set of low level HTTP transport components."/>
<attribute name="System-Bundle" value="yes"/>
</manifest>
</jar>
</target>
<!--BUNDLE-HTTPCLIENT -->
<target name="bundle-httpclient">
<jar compress="true" destfile="${bundles.dest}/httpclient.jar"
filesetmanifest="merge">
<zipfileset src="${lib.noinst}/httpclient-4.0.1.jar" prefix=""/>
<manifest>
<attribute name="Export-Package"
value="org.apache.http.annotation,
org.apache.http.auth,
org.apache.http.auth.params,
org.apache.http.client,
org.apache.http.client.entity,
org.apache.http.client.methods,
org.apache.http.client.params,
org.apache.http.client.protocol,
org.apache.http.client.utils,
org.apache.http.conn,
org.apache.http.conn.params,
org.apache.http.conn.routing,
org.apache.http.conn.scheme,
org.apache.http.conn.ssl,
org.apache.http.conn.util,
org.apache.http.impl.client"/>
<attribute name="Import-Package"
value="org.apache.commons.logging,
javax.net.ssl,
javax.security.auth.x500,
org.apache.http,
org.apache.http.entity,
org.apache.http.impl,
org.apache.http.impl.entity,
org.apache.http.impl.io,
org.apache.http.io,
org.apache.http.message,
org.apache.http.params,
org.apache.http.protocol,
org.apache.http.util"/>
<attribute name="Bundle-Name"
value="Apache HttpComponents Client"/>
<attribute name="Bundle-Description"
value="A set of low level HTTP transport components."/>
<attribute name="System-Bundle" value="yes"/>
</manifest>
<!--BUNDLE-HTTPUTIL -->
<target name="bundle-httputil">
<!-- Create the httputil.jar-->
<jar compress="false" destfile="${bundles.dest}/httputil.jar"
manifest="${src}/net/java/sip/communicator/service/httputil/httputil.manifest.mf">
<zipfileset dir="${dest}/net/java/sip/communicator/service/httputil"
prefix="net/java/sip/communicator/service/httputil"/>
<zipfileset src="${lib.noinst}/httpclient-4.1.1.jar" prefix=""/>
<zipfileset src="${lib.noinst}/httpcore-4.1.jar" prefix=""/>
<zipfileset src="${lib.noinst}/httpmime-4.1.1.jar" prefix=""/>
</jar>
</target>
@ -2346,11 +2285,11 @@ org.apache.http.util"/>
gnu.java.zrtp.utils,
gnu.java.zrtp.zidfile"/>
<attribute name="Import-Package" value="org.bouncycastle.asn1,
org.bouncycastle.asn1.nist,
org.bouncycastle.asn1.sec,
org.bouncycastle.asn1.x9,
org.bouncycastle.crypto,
org.bouncycastle.crypto.agreement,
org.bouncycastle.asn1.nist,
org.bouncycastle.asn1.sec,
org.bouncycastle.asn1.x9,
org.bouncycastle.crypto,
org.bouncycastle.crypto.agreement,
org.bouncycastle.crypto.digests,
org.bouncycastle.crypto.engines,
org.bouncycastle.crypto.generators,

@ -15,8 +15,9 @@
<classpathentry kind="lib" path="lib/installer-exclude/jmdns.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/dnsjava.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/fmj.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/httpclient-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/httpcore-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/httpclient-4.1.1.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/httpcore-4.1.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/httpmime-4.1.1.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/jain-sip-api.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/jain-sip-ri.jar"/>
<classpathentry kind="lib" path="lib/installer-exclude/jcalendar-1.3.2.jar"/>

@ -123,7 +123,7 @@
<compilation-unit>
<package-root>src</package-root>
<classpath
mode="compile">lib/felix.jar:lib/jdic-all.jar:lib/bundle/junit.jar:lib/bundle/log4j.jar:lib/bundle/commons-logging.jar:lib/installer-exclude/concurrent.jar:lib/installer-exclude/dict4j.jar:lib/installer-exclude/dnsjava.jar:lib/installer-exclude/jain-sip-api.jar:lib/installer-exclude/jain-sip-ri.jar:lib/installer-exclude/jain-sdp.jar:lib/installer-exclude/jcalendar-1.3.2.jar:lib/installer-exclude/jdic_misc.jar:lib/installer-exclude/jdom.jar:lib/installer-exclude/jmf.jar:lib/installer-exclude/jml-1.0b5.jar:lib/installer-exclude/joscar-client.jar:lib/installer-exclude/joscar-common.jar:lib/installer-exclude/joscar-protocol.jar:lib/installer-exclude/jsocks-klea.jar:lib/installer-exclude/jspeex.jar:lib/installer-exclude/junit.jar:lib/installer-exclude/log4j-1.2.8.jar:lib/installer-exclude/nist-sdp-1.0.jar:lib/installer-exclude/rome-0.9.jar:lib/installer-exclude/smack.jar:lib/installer-exclude/smackx.jar:lib/installer-exclude/ymsg_network_v0_67.jar:lib/installer-exclude/fmj.jar:lib/installer-exclude/jna.jar:lib/installer-exclude/lti-civil-no_s_w_t.jar:lib/installer-exclude/swing-worker-1.2.jar:lib/os-specific/linux/installer-exclude/jmf.jar:lib/os-specific/linux/jdic_stub.jar:lib/os-specific/mac/OrangeExtensions.jar:lib/os-specific/mac/growl4j.jar:lib/os-specific/mac/jdic_stub.jar:lib/os-specific/mac/installer-exclude/jmf.jar:lib/os-specific/mac/installer-exclude/dock.jar:lib/os-specific/windows/jdic_stub.jar:lib/os-specific/windows/installer-exclude/jmf.jar:lib/os-specific/windows/installer-exclude/sound.jar:lib/os-specific/windows/installer-exclude/jna-platform-win32.jar:lib/installer-exclude/aclibico-2.1.jar:lib/installer-exclude/jdic_misc.jar:lib/installer-exclude/pircbot.jar:lib/os-specific/solaris/jdic_stub.jar:lib/os-specific/solaris/installer-exclude/jmf.jar:lib/installer-exclude/jsch-0.1.36.jar:lib/installer-exclude/apache-ant-1.7.0.jar:lib/installer-exclude/jfontchooser-1.0.5.jar:lib/installer-exclude/laf-widget.jar:lib/installer-exclude/transparency.jar:lib/installer-exclude/zrtp4j-light.jar:lib/installer-exclude/lcrypto-jdk16-143.jar:lib/installer-exclude/otr4j.jar:lib/installer-exclude/profiler4j-1.0-beta3-SC.jar:lib/installer-exclude/httpcore-4.0.1.jar:lib/installer-exclude/httpclient-4.0.1.jar:lib/installer-exclude/json-20090723.jar:lib/installer-exclude/ice4j.jar:lib/installer-exclude/dhcp4java-1.00.jar:lib/installer-exclude/jmdns.jar:lib/installer-exclude/jmyspell-core.jar:lib/installer-exclude/jnsapi.jar:lib/installer-exclude/mac_widgets-0.9.5.jar:lib/installer-exclude/forms-1.2.1.jar:lib/installer-exclude/weupnp-0.1.2-SNAPSHOT.jar:lib/installer-exclude/libphonenumber-2.4.jar</classpath>
mode="compile">lib/felix.jar:lib/jdic-all.jar:lib/bundle/junit.jar:lib/bundle/log4j.jar:lib/bundle/commons-logging.jar:lib/installer-exclude/concurrent.jar:lib/installer-exclude/dict4j.jar:lib/installer-exclude/dnsjava.jar:lib/installer-exclude/jain-sip-api.jar:lib/installer-exclude/jain-sip-ri.jar:lib/installer-exclude/jain-sdp.jar:lib/installer-exclude/jcalendar-1.3.2.jar:lib/installer-exclude/jdic_misc.jar:lib/installer-exclude/jdom.jar:lib/installer-exclude/jmf.jar:lib/installer-exclude/jml-1.0b5.jar:lib/installer-exclude/joscar-client.jar:lib/installer-exclude/joscar-common.jar:lib/installer-exclude/joscar-protocol.jar:lib/installer-exclude/jsocks-klea.jar:lib/installer-exclude/jspeex.jar:lib/installer-exclude/junit.jar:lib/installer-exclude/log4j-1.2.8.jar:lib/installer-exclude/nist-sdp-1.0.jar:lib/installer-exclude/rome-0.9.jar:lib/installer-exclude/smack.jar:lib/installer-exclude/smackx.jar:lib/installer-exclude/ymsg_network_v0_67.jar:lib/installer-exclude/fmj.jar:lib/installer-exclude/jna.jar:lib/installer-exclude/lti-civil-no_s_w_t.jar:lib/installer-exclude/swing-worker-1.2.jar:lib/os-specific/linux/installer-exclude/jmf.jar:lib/os-specific/linux/jdic_stub.jar:lib/os-specific/mac/OrangeExtensions.jar:lib/os-specific/mac/growl4j.jar:lib/os-specific/mac/jdic_stub.jar:lib/os-specific/mac/installer-exclude/jmf.jar:lib/os-specific/mac/installer-exclude/dock.jar:lib/os-specific/windows/jdic_stub.jar:lib/os-specific/windows/installer-exclude/jmf.jar:lib/os-specific/windows/installer-exclude/sound.jar:lib/os-specific/windows/installer-exclude/jna-platform-win32.jar:lib/installer-exclude/aclibico-2.1.jar:lib/installer-exclude/jdic_misc.jar:lib/installer-exclude/pircbot.jar:lib/os-specific/solaris/jdic_stub.jar:lib/os-specific/solaris/installer-exclude/jmf.jar:lib/installer-exclude/jsch-0.1.36.jar:lib/installer-exclude/apache-ant-1.7.0.jar:lib/installer-exclude/jfontchooser-1.0.5.jar:lib/installer-exclude/laf-widget.jar:lib/installer-exclude/transparency.jar:lib/installer-exclude/zrtp4j-light.jar:lib/installer-exclude/lcrypto-jdk16-143.jar:lib/installer-exclude/otr4j.jar:lib/installer-exclude/profiler4j-1.0-beta3-SC.jar:lib/installer-exclude/httpcore-4.1.jar:lib/installer-exclude/httpmime-4.1.1.jar:lib/installer-exclude/httpclient-4.1.1.jar:lib/installer-exclude/json-20090723.jar:lib/installer-exclude/ice4j.jar:lib/installer-exclude/dhcp4java-1.00.jar:lib/installer-exclude/jmdns.jar:lib/installer-exclude/jmyspell-core.jar:lib/installer-exclude/jnsapi.jar:lib/installer-exclude/mac_widgets-0.9.5.jar:lib/installer-exclude/forms-1.2.1.jar:lib/installer-exclude/weupnp-0.1.2-SNAPSHOT.jar:lib/installer-exclude/libphonenumber-2.4.jar</classpath>
<built-to>classes</built-to>
<source-level>1.5</source-level>
</compilation-unit>

@ -37,6 +37,9 @@ felix.auto.start.20= \
felix.auto.start.30= \
reference:file:sc-bundles/fileaccess.jar
felix.auto.start.35= \
reference:file:sc-bundles/httputil.jar
felix.auto.start.40= \
reference:file:sc-bundles/configuration.jar \
reference:file:sc-bundles/jmdnslib.jar \
@ -69,8 +72,6 @@ felix.auto.start.49= \
reference:file:sc-bundles/zrtp4j.jar \
reference:file:sc-bundles/protocol.jar \
reference:file:sc-bundles/protocol-media.jar \
reference:file:sc-bundles/httpcore.jar \
reference:file:sc-bundles/httpclient.jar \
reference:file:sc-bundles/hid.jar \
reference:file:sc-bundles/globalproxyconfig.jar
@ -160,7 +161,7 @@ felix.auto.start.70= \
reference:file:sc-bundles/simpleaccreg.jar \
reference:file:sc-bundles/securityconfig.jar \
reference:file:sc-bundles/ippiaccregwizz.jar \
reference:file:sc-bundles/iptelaccregwizz.jar
reference:file:sc-bundles/iptelaccregwizz.jar
felix.auto.start.75= \
reference:file:sc-bundles/argdelegation.jar

@ -5,21 +5,18 @@
*/
package net.java.sip.communicator.plugin.loggingutils;
import com.sun.jndi.toolkit.url.*;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.notification.*;
import net.java.sip.communicator.service.packetlogging.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import javax.net.ssl.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
/**
@ -697,129 +694,29 @@ static void uploadLogs(
if(uploadLocation == null)
return;
URL url = new URL(uploadLocation);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection))
return;
HttpURLConnection conn = (HttpURLConnection)urlConn;
if(urlConn instanceof HttpsURLConnection)
if(HttpUtils.postFile(uploadLocation, "logs", newDest) != null)
{
CertificateVerificationService vs =
LoggingUtilsActivator.getCertificateVerificationService();
int port = url.getPort();
/* if we do not specify port in the URL
* (http://domain.org:port) we have to set up the default
* port of HTTP (80) or
* HTTPS (443).
*/
if(port == -1)
{
if(url.getProtocol().equals("http"))
{
port = 80;
}
else if(url.getProtocol().equals("https"))
{
port = 443;
}
}
((HttpsURLConnection)urlConn).setSSLSocketFactory(
vs.getSSLContext(
url.getHost(), port).getSocketFactory());
}
NotificationService notificationService
= LoggingUtilsActivator.getNotificationService();
Random random = new Random();
String boundary = "---------------------------" +
Long.toString(random.nextLong(), 36) +
Long.toString(random.nextLong(), 36) +
Long.toString(random.nextLong(), 36);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = conn.getOutputStream();
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("\r\n".getBytes());
out.write("Content-Disposition: form-data; name=\"".getBytes());
out.write("logs".getBytes());
out.write('"');
out.write("; filename=\"".getBytes());
out.write(newDest.getPath().getBytes());
out.write('"');
out.write("\r\n".getBytes());
out.write("Content-Type: ".getBytes());
String type = conn.guessContentTypeFromName(newDest.getPath());
if (type == null)
type = "application/octet-stream";
out.write(type.getBytes());
out.write("\r\n".getBytes());
out.write("\r\n".getBytes());
byte[] buf = new byte[4096];
int nread;
FileInputStream in = new FileInputStream(newDest);
while((nread = in.read(buf, 0, buf.length)) >= 0)
{
out.write(buf, 0, nread);
}
out.flush();
buf = null;
out.write("\r\n".getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("--".getBytes());
out.write("\r\n".getBytes());
out.close();
InputStream serverInput = conn.getInputStream();
// Get response data.
BufferedReader input =
new BufferedReader(new InputStreamReader(serverInput));
if(logger.isDebugEnabled())
{
logger.debug("Log files uploaded result:");
String str;
while((str = input.readLine()) != null)
if(notificationService != null)
{
logger.debug(str);
String bodyMsgKey = "plugin.loggingutils.ARCHIVE_MESSAGE_OK";
ResourceManagementService resources =
LoggingUtilsActivator.getResourceService();
notificationService.fireNotification(
LOGFILES_ARCHIVED,
resources.getI18NString(
"plugin.loggingutils.ARCHIVE_BUTTON"),
resources.getI18NString(
bodyMsgKey,
new String[]{uploadLocation}),
null,
null);
}
}
input.close ();
NotificationService notificationService
= LoggingUtilsActivator.getNotificationService();
if(notificationService != null)
{
String bodyMsgKey = "plugin.loggingutils.ARCHIVE_MESSAGE_OK";
ResourceManagementService resources =
LoggingUtilsActivator.getResourceService();
notificationService.fireNotification(
LOGFILES_ARCHIVED,
resources.getI18NString(
"plugin.loggingutils.ARCHIVE_BUTTON"),
resources.getI18NString(
bodyMsgKey,
new String[]{uploadLocation}),
null,
null);
}
}
catch(Throwable e)
{

@ -61,11 +61,6 @@ public class LoggingUtilsActivator
*/
private static NotificationService notificationService;
/**
* Reference to the <tt>CertificateVerificationService</tt>.
*/
private static CertificateVerificationService certificateService = null;
/**
* Creates and register logging configuration.
*
@ -203,26 +198,4 @@ public static NotificationService getNotificationService()
}
return notificationService;
}
/**
* Return the certificate verification service impl.
* @return the CertificateVerification service.
*/
public static CertificateVerificationService
getCertificateVerificationService()
{
if(certificateService == null)
{
ServiceReference certVerifyReference
= bundleContext.getServiceReference(
CertificateVerificationService.class.getName());
if(certVerifyReference != null)
certificateService
= (CertificateVerificationService)bundleContext.getService(
certVerifyReference);
}
return certificateService;
}
}

@ -5,10 +5,10 @@ Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
System-Bundle: yes
Import-Package: org.osgi.framework,
net.java.sip.communicator.service.certificate,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.fileaccess,
net.java.sip.communicator.service.gui,
net.java.sip.communicator.service.httputil,
net.java.sip.communicator.service.notification,
net.java.sip.communicator.service.packetlogging,
net.java.sip.communicator.service.resources,

@ -10,19 +10,17 @@
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
import javax.swing.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.credentialsstorage.*;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.provdisc.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import org.osgi.framework.*;
@ -99,11 +97,6 @@ public class ProvisioningActivator
*/
private static CredentialsStorageService credentialsService = null;
/**
* The service we use to interact with user for SSL certificate stuff.
*/
private static CertificateVerificationService certVerification = null;
/**
* A reference to the NetworkAddressManagerService implementation instance
* that is registered with the bundle context.
@ -336,156 +329,6 @@ public static ResourceManagementService getResourceService()
return resourceService;
}
/**
* Configure HTTP connection to provide HTTP authentication and SSL
* truster.
*
* @param url provisioning URL
* @param connection the <tt>URLConnection</tt>
*/
private void configureHTTPConnection(URL url, HttpURLConnection connection)
{
try
{
connection.setRequestMethod(method);
if(method.equals("POST"))
{
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
}
if(connection instanceof HttpsURLConnection)
{
CertificateVerificationService vs =
getCertificateVerificationService();
int port = url.getPort();
/* if we do not specify port in the URL (http://domain.org:port)
* we have to set up the default port of HTTP (80) or
* HTTPS (443).
*/
if(port == -1)
{
if(url.getProtocol().equals("http"))
{
port = 80;
}
else if(url.getProtocol().equals("https"))
{
port = 443;
}
}
((HttpsURLConnection)connection).setSSLSocketFactory(
vs.getSSLContext(
url.getHost(), port).getSocketFactory());
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName,
SSLSession session)
{
logger.warn("Warning: URL Host: " + urlHostName +
" vs. " + session.getPeerHost());
return true;
}
};
((HttpsURLConnection)connection).setHostnameVerifier(hv);
}
}
catch (Exception e)
{
logger.warn("Failed to initialize secure connection", e);
}
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
// if there is something save return it
ConfigurationService config = getConfigurationService();
CredentialsStorageService credStorage =
getCredentialsStorageService();
String uName
= (String) config.getProperty(
PROPERTY_PROVISIONING_USERNAME);
if(uName != null)
{
String pass = credStorage.loadPassword(
PROPERTY_PROVISIONING_PASSWORD);
if(pass != null)
return new PasswordAuthentication(uName,
pass.toCharArray());
}
if(userCredentials != null)
{
return new PasswordAuthentication(
userCredentials.getUserName(),
userCredentials.getPassword());
}
else
{
return null;
}
}
});
}
/**
* Handle authentication with the provisioning server.
*/
private void handleProvisioningAuth()
{
ConfigurationService configService = getConfigurationService();
CredentialsStorageService credService =
getCredentialsStorageService();
String username = configService.getString(
PROPERTY_PROVISIONING_USERNAME);
String password = credService.loadPassword(
PROPERTY_PROVISIONING_PASSWORD);
if(username != null && password != null)
{
/* we have already the credentials stored so return them */
userCredentials = new UserCredentials();
userCredentials.setUserName(username);
userCredentials.setPassword(password.toCharArray());
userCredentials.setPasswordPersistent(true);
return;
}
AuthenticationWindow authWindow = new AuthenticationWindow(
"provisioning", true, null);
authWindow.setVisible(true);
if(!authWindow.isCanceled())
{
userCredentials = new UserCredentials();
userCredentials.setUserName(authWindow.getUserName());
userCredentials.setPassword(authWindow.getPassword());
userCredentials.setPasswordPersistent(
authWindow.isRememberPassword());
if(userCredentials.getUserName() == null)
{
userCredentials = null;
}
}
else
{
userCredentials = null;
}
}
/**
* Retrieve configuration file from provisioning URL.
* This method is blocking until configuration file is retrieved from the
@ -521,202 +364,126 @@ private File retrieveConfigurationFile(String url)
}
URL u = new URL(url);
URLConnection uc = u.openConnection();
OutputStreamWriter out = null;
if(uc instanceof HttpURLConnection)
InetAddress ipaddr = getNetworkAddressManagerService().
getLocalHost(InetAddress.getByName(u.getHost()));
String[] paramNames = null;
String[] paramValues = null;
int usernameIx = -1;
int passwordIx = -1;
if(args != null && args.length > 0)
{
configureHTTPConnection(u, (HttpURLConnection)uc);
((HttpURLConnection)uc).setInstanceFollowRedirects(false);
uc.setDoInput(true);
uc.setDoOutput(true);
out = new OutputStreamWriter(uc.getOutputStream());
/* send out (via GET or POST) */
StringBuffer content = new StringBuffer();
InetAddress ipaddr = getNetworkAddressManagerService().
getLocalHost(InetAddress.getByName(u.getHost()));
if(args != null && args.length > 0)
paramNames = new String[args.length];
paramValues = new String[args.length];
for(int i = 0; i < args.length; i++)
{
for(String s : args)
String s = args[i];
if(s.equals("username=$username") ||
s.equals("username"))
{
if(s.equals("username=$username") ||
s.equals("username"))
{
if(userCredentials == null)
{
handleProvisioningAuth();
}
content.append("username=" +
URLEncoder.encode(
userCredentials.getUserName(),
"UTF-8"));
}
else if(s.equals("password=$password") ||
s.equals("password"))
{
if(userCredentials == null)
{
handleProvisioningAuth();
}
paramNames[i] = "username";
paramValues[i] = "";
usernameIx = i;
}
else if(s.equals("password=$password") ||
s.equals("password"))
{
paramNames[i] = "password";
paramValues[i] = "";
passwordIx = i;
}
else if(s.equals("osname=$osname") ||
s.equals("osname"))
{
paramNames[i] = "osname";
paramValues[i] = System.getProperty("os.name");
}
else if(s.equals("build=$build") ||
s.equals("build"))
{
paramNames[i] = "build";
paramValues[i] =
System.getProperty("sip-communicator.version");
}
else if(s.equals("ipaddr=$ipaddr") ||
s.equals("ipaddr"))
{
paramNames[i] = "ipaddr";
paramValues[i] = ipaddr.getHostAddress();
}
else if(s.equals("hwaddr=$hwaddr") ||
s.equals("hwaddr"))
{
paramNames[i] = "hwaddr";
content.append("password=" +
URLEncoder.encode(
userCredentials.
getPasswordAsString(),
"UTF-8"));
}
else if(s.equals("osname=$osname") ||
s.equals("osname"))
if(ipaddr != null)
{
content.append("osname=" + URLEncoder.encode(
System.getProperty("os.name"), "UTF-8"));
}
else if(s.equals("build=$build") ||
s.equals("build"))
{
content.append("build=" + URLEncoder.encode(
System.getProperty("sip-communicator.version"),
"UTF-8"));
}
else if(s.equals("ipaddr=$ipaddr") ||
s.equals("ipaddr"))
{
content.append("ipaddr=" + URLEncoder.encode(
ipaddr.getHostAddress(), "UTF-8"));
}
else if(s.equals("hwaddr=$hwaddr") ||
s.equals("hwaddr"))
{
String hwaddr = null;
/* find the hardware address of the interface
* that has this IP address
*/
Enumeration<NetworkInterface> en =
NetworkInterface.getNetworkInterfaces();
if(ipaddr != null)
while(en.hasMoreElements())
{
/* find the hardware address of the interface
* that has this IP address
*/
Enumeration<NetworkInterface> en =
NetworkInterface.getNetworkInterfaces();
NetworkInterface iface = en.nextElement();
while(en.hasMoreElements())
{
NetworkInterface iface = en.nextElement();
Enumeration<InetAddress> enInet =
iface.getInetAddresses();
Enumeration<InetAddress> enInet =
iface.getInetAddresses();
while(enInet.hasMoreElements())
{
InetAddress inet = enInet.nextElement();
while(enInet.hasMoreElements())
if(inet.equals(ipaddr))
{
InetAddress inet = enInet.nextElement();
byte hw[] =
getNetworkAddressManagerService().
getHardwareAddress(iface);
StringBuffer buf =
new StringBuffer();
if(inet.equals(ipaddr))
for(byte h : hw)
{
byte hw[] =
getNetworkAddressManagerService().
getHardwareAddress(iface);
StringBuffer buf =
new StringBuffer();
for(byte h : hw)
{
int hi = h >= 0 ? h : h + 256;
String t = new String(
(hi <= 0xf) ? "0" : "");
t += Integer.toHexString(hi);
buf.append(t);
buf.append(":");
}
buf.deleteCharAt(buf.length() - 1);
hwaddr = buf.toString();
content.append("hwaddr=" +
URLEncoder.encode(
hwaddr, "UTF-8"));
break;
int hi = h >= 0 ? h : h + 256;
String t = new String(
(hi <= 0xf) ? "0" : "");
t += Integer.toHexString(hi);
buf.append(t);
buf.append(":");
}
buf.deleteCharAt(buf.length() - 1);
paramValues[i] = buf.toString();
break;
}
}
}
}
content.append("&");
}
}
out.write(content.toString());
out.flush();
int responseCode = ((HttpURLConnection)uc).getResponseCode();
if(responseCode == HttpURLConnection.HTTP_UNAUTHORIZED)
{
/* remove stored username and password if authorization
* failed
*/
getConfigurationService().removeProperty(
PROPERTY_PROVISIONING_USERNAME);
getCredentialsStorageService().removePassword(
PROPERTY_PROVISIONING_PASSWORD);
AuthenticationWindow authWindow = new AuthenticationWindow(
u.getHost(), true, null);
authWindow.setVisible(true);
userCredentials = new UserCredentials();
userCredentials.setUserName(authWindow.getUserName());
userCredentials.setPassword(authWindow.getPassword());
userCredentials.setPasswordPersistent(
authWindow.isRememberPassword());
if(userCredentials.getUserName() == null)
{
userCredentials = null;
}
else
{
tmpFile.delete();
return retrieveConfigurationFile(url);
}
}
else if(responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
responseCode == HttpURLConnection.HTTP_MOVED_TEMP)
{
String loc =
((HttpURLConnection)uc).getHeaderField("Location");
if(loc != null && (loc.startsWith("http://") ||
loc.startsWith("https://")))
{
tmpFile.delete();
/* TODO detect loops */
return retrieveConfigurationFile(loc);
paramNames[i] = "";
paramValues[i] = "";
}
}
else if(responseCode == HttpURLConnection.HTTP_OK)
{
if(userCredentials != null &&
userCredentials.getUserName() != null &&
userCredentials.isPasswordPersistent())
{
// if save password is checked save the pass
getConfigurationService().setProperty(
PROPERTY_PROVISIONING_USERNAME,
userCredentials.getUserName());
getCredentialsStorageService().storePassword(
PROPERTY_PROVISIONING_PASSWORD,
userCredentials.getPasswordAsString());
}
}
}
else
{
return null;
}
InputStream in = uc.getInputStream();
HttpUtils.HTTPResponseResult res =
HttpUtils.postForm(
url,
PROPERTY_PROVISIONING_USERNAME,
PROPERTY_PROVISIONING_PASSWORD,
paramNames,
paramValues,
usernameIx,
passwordIx);
InputStream in = res.getContent();
// Chain a ProgressMonitorInputStream to the
// URLConnection's InputStream
@ -725,7 +492,7 @@ else if(responseCode == HttpURLConnection.HTTP_OK)
// Set the maximum value of the ProgressMonitor
ProgressMonitor pm = pin.getProgressMonitor();
pm.setMaximum(uc.getContentLength());
pm.setMaximum((int)res.getContentLength());
final BufferedOutputStream bout
= new BufferedOutputStream(new FileOutputStream(temp));
@ -743,7 +510,6 @@ else if(responseCode == HttpURLConnection.HTTP_OK)
pin.close();
bout.flush();
bout.close();
out.close();
return temp;
}
@ -755,7 +521,6 @@ else if(responseCode == HttpURLConnection.HTTP_OK)
{
pin.close();
bout.close();
out.close();
}
catch (Exception e1)
{
@ -950,27 +715,6 @@ private void checkEnforcePrefix(String enforcePrefix)
}
}
/**
* Return the certificate verification service impl.
* @return the CertificateVerification service.
*/
private static CertificateVerificationService
getCertificateVerificationService()
{
if(certVerification == null)
{
ServiceReference certVerifyReference
= bundleContext.getServiceReference(
CertificateVerificationService.class.getName());
if(certVerifyReference != null)
certVerification
= (CertificateVerificationService)bundleContext.getService(
certVerifyReference);
}
return certVerification;
}
/**
* Returns a reference to a ConfigurationService implementation currently
* registered in the bundle context or null if no such implementation was

@ -8,11 +8,11 @@ Import-Package: org.osgi.framework,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.gui,
net.java.sip.communicator.service.gui.event,
net.java.sip.communicator.service.httputil,
net.java.sip.communicator.service.resources,
net.java.sip.communicator.service.provdisc,
net.java.sip.communicator.service.protocol,
net.java.sip.communicator.service.netaddr,
net.java.sip.communicator.service.certificate,
net.java.sip.communicator.service.credentialsstorage,
net.java.sip.communicator.util,
net.java.sip.communicator.util.swing,

@ -12,15 +12,14 @@
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
import javax.swing.*;
import javax.swing.text.*;
import net.java.sip.communicator.service.browserlauncher.*;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.Container; // disambiguation
import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.service.shutdown.*;
@ -71,11 +70,6 @@ public class UpdateCheckActivator
*/
private static UIService uiService = null;
/**
* Reference to the <tt>CertificateVerificationService</tt>.
*/
private static CertificateVerificationService certificateVerification = null;
/**
* The download link of the update.
*/
@ -156,11 +150,6 @@ public class UpdateCheckActivator
*/
private int inCheckForUpdates = 0;
static
{
removeDownloadRestrictions();
}
/**
* Starts this bundle
*
@ -298,23 +287,6 @@ private static ResourceManagementService getResources()
return resources;
}
/**
* Returns the certificate verification service implementation.
*
* @return the <tt>CertificateVerificationService</tt>
*/
private static CertificateVerificationService getCertificateVerification()
{
if(certificateVerification == null)
{
certificateVerification
= ServiceUtils.getService(
bundleContext,
CertificateVerificationService.class);
}
return certificateVerification;
}
/**
* Checks the first link as files on the web are sorted by date.
*
@ -347,43 +319,18 @@ private boolean isNewestVersion()
return true;
}
URL url = new URL(configString);
URLConnection conn = url.openConnection();
Properties props = new Properties();
HttpUtils.HTTPResponseResult res
= HttpUtils.openURLConnection(configString);
if (conn instanceof HttpURLConnection)
{
while(((HttpURLConnection)conn).getResponseCode() ==
HttpURLConnection.HTTP_UNAUTHORIZED
&& !isAuthenticationCanceled)
{
if(userCredentials.getUserName() != null)
{
errorMessage = getResources().getI18NString(
"service.gui.AUTHENTICATION_FAILED",
new String[]{
userCredentials.getUserName(),
host});
userCredentials.setUserName(null);
userCredentials.setPasswordPersistent(false);
userCredentials = null;
getConfiguration().removeProperty(
UPDATE_USERNAME_CONFIG);
getConfiguration().removeProperty(
UPDATE_PASSWORD_CONFIG);
conn = url.openConnection();
}
else
break;
}
}
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
if(res == null)
return true;
Properties props = new Properties();
props.load(conn.getInputStream());
InputStream in = res.getContent();
props.load(in);
in.close();
lastVersion = props.getProperty("last_version");
downloadLink = props.getProperty("download_link");
@ -764,47 +711,22 @@ private void windowsUpdate()
tempFileOutputStream = createTempFileOutputStream(u, tempFile);
URLConnection uc = u.openConnection();
HttpUtils.HTTPResponseResult res
= HttpUtils.openURLConnection(downloadLink);
if (uc instanceof HttpURLConnection)
{
if(uc instanceof HttpsURLConnection)
{
CertificateVerificationService cvs
= getCertificateVerification();
if(res == null)
return;
int port = u.getPort();
/*
* If we do not specify port in the URL, we have to set up
* the default port of HTTP (80) or HTTPS (443).
*/
if(port == -1)
{
if(u.getProtocol().equals("http"))
port = 80;
else if(u.getProtocol().equals("https"))
port = 443;
}
((HttpsURLConnection)uc).setSSLSocketFactory(
cvs.getSSLContext(u.getHost(), port)
.getSocketFactory());
}
// we don't handle here authentication fails cause
// still we gone to downloading file we have gone through
// successful authentication
}
InputStream in = res.getContent();
// Track the progress of the download.
final ProgressMonitorInputStream input
= new ProgressMonitorInputStream(
null,
u.toString(),
uc.getInputStream());
downloadLink,
in);
// Set the maximum value of the ProgressMonitor
input.getProgressMonitor().setMaximum(uc.getContentLength());
input.getProgressMonitor().setMaximum((int)res.getContentLength());
final BufferedOutputStream output
= new BufferedOutputStream(tempFileOutputStream);
@ -1130,121 +1052,6 @@ private synchronized void exitCheckForUpdates(JDialog checkForUpdatesDialog)
}
}
/**
* Installs Dummy TrustManager will not try to validate self-signed certs.
* Fix some problems with not proper use of certs.
*/
private static void removeDownloadRestrictions()
{
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
logger.warn("Warning: URL Host: " + urlHostName +
" vs. " + session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
if(userCredentials == null)
{
// if there is something save return it
ConfigurationService config = getConfiguration();
String uName
= (String) config.getProperty(UPDATE_USERNAME_CONFIG);
if(uName != null)
{
String pass
= (String) config.getProperty(UPDATE_PASSWORD_CONFIG);
if(pass != null)
{
userCredentials = new UserCredentials();
userCredentials.setUserName(uName);
userCredentials.setPassword(new String(
Base64.decode(pass)).toCharArray());
userCredentials.setPasswordPersistent(true);
}
}
}
if(userCredentials != null)
{
return new PasswordAuthentication(
userCredentials.getUserName(),
userCredentials.getPassword());
}
else
{
host = getRequestingHost();
AuthenticationWindow authWindow = null;
if(errorMessage == null)
{
authWindow = new AuthenticationWindow(host, true, null);
}
else
{
authWindow = new AuthenticationWindow(
null, null, host, true, null, errorMessage);
// we showed the message, remove it
errorMessage = null;
}
userCredentials = new UserCredentials();
authWindow.setVisible(true);
if (!authWindow.isCanceled())
{
isAuthenticationCanceled = false;
userCredentials.setUserName(authWindow.getUserName());
userCredentials.setPassword(authWindow.getPassword());
userCredentials.setPasswordPersistent(
authWindow.isRememberPassword());
if(authWindow.isRememberPassword())
{
// if save password is checked save the pass
getConfiguration().setProperty(
UPDATE_USERNAME_CONFIG,
userCredentials.getUserName());
getConfiguration().setProperty(
UPDATE_PASSWORD_CONFIG,
new String(
Base64.encode(
userCredentials
.getPasswordAsString()
.getBytes())));
}
return new PasswordAuthentication(
userCredentials.getUserName(),
userCredentials.getPassword());
}
else
{
isAuthenticationCanceled = true;
userCredentials.setUserName(null);
userCredentials = null;
getConfiguration().removeProperty(
UPDATE_USERNAME_CONFIG);
getConfiguration().removeProperty(
UPDATE_PASSWORD_CONFIG);
}
return null;
}
}
});
}
/**
* Implements <tt>PluginComponent</tt> for the "Check for Updates" menu
* item.

@ -6,8 +6,8 @@ Bundle-Version: 0.0.1
System-Bundle: yes
Import-Package: org.osgi.framework,
net.java.sip.communicator.service.browserlauncher,
net.java.sip.communicator.service.certificate,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.httputil,
net.java.sip.communicator.service.gui,
net.java.sip.communicator.service.protocol,
net.java.sip.communicator.service.resources,

@ -0,0 +1,143 @@
package net.java.sip.communicator.service.httputil;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.credentialsstorage.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* The http utils bundle activator. Do nothing just provide access to some
* services.
*
* @author Damian Minkov
*/
public class HttpUtilActivator
implements BundleActivator
{
/**
* The service we use to interact with user regarding certificates.
*/
private static CertificateVerificationService guiCertificateVerification;
/**
* Reference to the credentials service
*/
private static CredentialsStorageService credentialsService;
/**
* The bundle context.
*/
private static BundleContext bundleContext;
/**
* The resource service.
*/
private static ResourceManagementService resourceService;
/**
* A reference to the ConfigurationService implementation instance that
* is currently registered with the bundle context.
*/
private static ConfigurationService configurationService;
/**
* Return the certificate verification service impl.
* @return the CertificateVerification service.
*/
public static CertificateVerificationService
getCertificateVerificationService()
{
if(guiCertificateVerification == null)
{
ServiceReference guiVerifyReference
= bundleContext.getServiceReference(
CertificateVerificationService.class.getName());
if(guiVerifyReference != null)
guiCertificateVerification = (CertificateVerificationService)
bundleContext.getService(guiVerifyReference);
}
return guiCertificateVerification;
}
/**
* Returns a reference to a CredentialsStorageConfigurationService
* implementation currently registered in the bundle context or null if no
* such implementation was found.
*
* @return a currently valid implementation of the
* CredentialsStorageService.
*/
public static CredentialsStorageService getCredentialsService()
{
if(credentialsService == null)
{
ServiceReference confReference
= bundleContext.getServiceReference(
CredentialsStorageService.class.getName());
credentialsService
= (CredentialsStorageService) bundleContext.getService(
confReference);
}
return credentialsService;
}
/**
* Start the bundle.
* @param bundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext)
throws
Exception
{
HttpUtilActivator.bundleContext = bundleContext;
}
/**
* Stops the bundle.
* @param bundleContext
* @throws Exception
*/
public void stop(BundleContext bundleContext)
throws
Exception
{
}
/**
* Returns the service giving access to all application resources.
*
* @return the service giving access to all application resources.
*/
public static ResourceManagementService getResources()
{
if (resourceService == null)
{
resourceService
= ResourceManagementServiceUtils.getService(bundleContext);
}
return resourceService;
}
/**
* Returns a reference to a ConfigurationService implementation currently
* registered in the bundle context or null if no such implementation was
* found.
*
* @return a currently valid implementation of the ConfigurationService.
*/
public static ConfigurationService getConfigurationService()
{
if (configurationService == null)
{
configurationService
= ServiceUtils.getService(
bundleContext,
ConfigurationService.class);
}
return configurationService;
}
}

@ -0,0 +1,712 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.httputil;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.*;
import org.apache.http.message.*;
import org.apache.http.params.*;
import org.apache.http.protocol.*;
import org.apache.http.util.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Common http utils querying http locations, handling redirects, self-signed
* certificates, host verify on certificates, password protection and storing
* and reusing credentials for password protected sites.
*
* @author Damian Minkov
*/
public class HttpUtils
{
/**
* The <tt>Logger</tt> used by the <tt>HttpUtils</tt> class for logging
* output.
*/
private static final Logger logger = Logger.getLogger(HttpUtils.class);
/**
* The prefix used when storing credentials for sites when no property
* is provided.
*/
private static final String HTTP_CREDENTIALS_PREFIX =
"net.java.sip.communicator.util.http.credential.";
/**
* Opens a connection to the <tt>address</tt>.
* @param address the address to contact.
* @return the result if any or null if connection was not possible
* or canceled by user.
*/
public static HTTPResponseResult openURLConnection(String address)
{
return openURLConnection(address, null, null);
}
/**
* Opens a connection to the <tt>address</tt>.
* @param address the address to contact.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @return the result if any or null if connection was not possible
* or canceled by user.
*/
public static HTTPResponseResult openURLConnection(String address,
String usernamePropertyName,
String passwordPropertyName)
{
try
{
DefaultHttpClient httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName);
HttpEntity result = executeMethod(httpClient, new HttpGet(address));
if(result == null)
return null;
return new HTTPResponseResult(result, httpClient);
}
catch(Throwable t)
{
logger.error("Cannot open connection to:" + address, t);
}
return null;
}
/**
* Executes the metod and return the result. Handle ask for password
* when hitting password protected site.
* Keep asking for password till user clicks cancel or enters correct
* password. When 'remember password' is checked password is saved, if this
* password and username are not correct clear them, if there are correct
* they stay saved.
* @param httpClient the configured http client to use.
* @param req the request for now it is get or post.
* @return the result http entity.
*/
private static HttpEntity executeMethod(DefaultHttpClient httpClient,
HttpRequestBase req)
throws Throwable
{
// do it when response (first execution) or till we are unauthorized
HttpResponse response = null;
while(response == null
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_UNAUTHORIZED)
{
// if we were unauthorized, lets clear the method and recreate it
// for new connection with new credentials.
if(response != null)
{
if(logger.isDebugEnabled())
logger.debug("Will retry http connect and " +
"credentials input as latest are not correct!");
URI uri = req.getURI();
req.abort();
req = req.getClass().newInstance();
req.setURI(uri);
httpClient.getCredentialsProvider().clear();
response = httpClient.execute(req);
}
else
response = httpClient.execute(req);
// if user click cancel no need to retry, stop trying
if(!((HTTPCredentialsProvider)httpClient
.getCredentialsProvider()).retry())
{
if(logger.isDebugEnabled())
logger.debug("User canceled credentials input.");
break;
}
}
// if we finally managed to login return the result.
if(response != null
&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return response.getEntity();
}
// is user has canceled no result needed.
return null;
}
/**
* Posts a <tt>file</tt> to the <tt>address</tt>.
* @param address the address to post the form to.
* @param fileParamName the name of the param for the file.
* @param file the file we will send.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postFile(String address,
String fileParamName,
File file)
{
return postFile(address, fileParamName, file, null, null);
}
/**
* Posts a <tt>file</tt> to the <tt>address</tt>.
* @param address the address to post the form to.
* @param fileParamName the name of the param for the file.
* @param file the file we will send.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postFile(String address,
String fileParamName,
File file,
String usernamePropertyName,
String passwordPropertyName)
{
DefaultHttpClient httpClient = null;
try
{
httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName);
HttpPost postMethod = new HttpPost(address);
String mimeType = URLConnection.guessContentTypeFromName(
file.getPath());
if(mimeType == null)
mimeType = "application/octet-stream";
FileBody bin = new FileBody(file, mimeType);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(fileParamName, bin);
postMethod.setEntity(reqEntity);
HttpEntity resEntity = executeMethod(httpClient, postMethod);
if(resEntity == null)
return null;
if(logger.isDebugEnabled())
logger.debug("Post file response: "
+ EntityUtils.toString(resEntity));
return new HTTPResponseResult(reqEntity, httpClient);
}
catch(Throwable e)
{
logger.error("Cannot post file to:" + address, e);
}
return null;
}
/**
* Posting form to <tt>address</tt>. For submission we use POST method
* which is "application/x-www-form-urlencoded" encoded.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @param formParamNames the parameter names to include in post.
* @param formParamValues the corresponding parameter values to use.
* @param usernameParamIx the index of the username parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @param passwordParamIx the index of the password parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postForm(String address,
String usernamePropertyName,
String passwordPropertyName,
String[] formParamNames,
String[] formParamValues,
int usernameParamIx,
int passwordParamIx)
{
DefaultHttpClient httpClient = null;
try
{
httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName);
HttpPost postMethod = new HttpPost(address);
// if we have username and password in the parameters, lets
// retrieve their values
Credentials creds = null;
if(usernameParamIx != -1
&& usernameParamIx < formParamNames.length
&& passwordParamIx != -1
&& passwordParamIx < formParamNames.length)
{
URL url = new URL(address);
creds = new HTTPCredentialsProvider(
usernamePropertyName, passwordPropertyName)
.getCredentials(new AuthScope(
url.getHost(), url.getPort()));
}
// construct the name value pairs we will be sending
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for(int i = 0; i < formParamNames.length; i++)
{
// we are on the username index, insert retrieved username value
if(i == usernameParamIx && creds != null)
{
parameters.add(new BasicNameValuePair(
formParamNames[i], creds.getUserPrincipal().getName()));
}// we are on the password index, insert retrieved password val
else if(i == passwordParamIx && creds != null)
{
parameters.add(new BasicNameValuePair(
formParamNames[i], creds.getPassword()));
}
else // common name value pair, all info is present
{
parameters.add(new BasicNameValuePair(
formParamNames[i], formParamValues[i]));
}
}
String s = URLEncodedUtils.format(parameters, HTTP.UTF_8);
StringEntity entity = new StringEntity(s, HTTP.UTF_8);
// set content type to "application/x-www-form-urlencoded"
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
// insert post values encoded.
postMethod.setEntity(entity);
// execute post
HttpEntity resEntity = executeMethod(httpClient, postMethod);
// canceled or no result
if(resEntity == null)
return null;
if(logger.isDebugEnabled())
logger.debug("Post form response: "
+ EntityUtils.toString(resEntity));
return new HTTPResponseResult(resEntity, httpClient);
}
catch(Throwable e)
{
e.printStackTrace();
}
return null;
}
/**
* Returns the preconfigured http client,
* using CertificateVerificationService, timeouts, user-agent,
* hostname verifier, proxy settings are used from global java settings,
* if protected site is hit asks for credentials
* using util.swing.AuthenticationWindow.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
*/
private static DefaultHttpClient getHttpClient(
String usernamePropertyName,
String passwordPropertyName)
throws IOException
{
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpProtocolParams.setUserAgent(httpClient.getParams(),
System.getProperty("sip-communicator.application.name")
+ "/"
+ System.getProperty("sip-communicator.version"));
SSLContext sslCtx = HttpUtilActivator
.getCertificateVerificationService().getSSLContext(
HttpUtilActivator.getResources().
getI18NString(
"service.gui.CERT_DIALOG_CLIENT_DESCRIPTION_TXT",
new String[]
{
HttpUtilActivator.getResources().getSettingsString(
"service.gui.APPLICATION_NAME")
}));
Scheme sch = new Scheme("https", 443,
new SSLSocketFactory(
sslCtx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
// set proxy from default jre settings
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
httpClient.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
httpClient.setRoutePlanner(routePlanner);
HTTPCredentialsProvider credentialsProvider =
new HTTPCredentialsProvider(
usernamePropertyName, passwordPropertyName);
httpClient.setCredentialsProvider(credentialsProvider);
return httpClient;
}
/**
* The provider asking for password that is inserted into httpclient.
*/
private static class HTTPCredentialsProvider
implements CredentialsProvider
{
/**
* Should we continue retrying, this is set when user hits cancel.
*/
private boolean retry = true;
/**
* The last scope we have used, no problem overriding cause
* we use new HTTPCredentialsProvider instance for every
* httpclient/request.
*/
private AuthScope usedScope = null;
/**
* The property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
*/
private String usernamePropertyName = null;
/**
* The property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
*/
private String passwordPropertyName = null;
/**
* Creates HTTPCredentialsProvider.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
*/
HTTPCredentialsProvider(String usernamePropertyName,
String passwordPropertyName)
{
this.usernamePropertyName = usernamePropertyName;
this.passwordPropertyName = passwordPropertyName;
}
/**
* Not used.
*/
public void setCredentials(AuthScope authscope, Credentials credentials)
{}
/**
* Get the {@link org.apache.http.auth.Credentials credentials} for the
* given authentication scope.
*
* @param authscope the {@link org.apache.http.auth.AuthScope
* authentication scope}
* @return the credentials
* @see #setCredentials(org.apache.http.auth.AuthScope,
* org.apache.http.auth.Credentials)
*/
public Credentials getCredentials(AuthScope authscope)
{
this.usedScope = authscope;
// if we have specified password and username property will use them
// if not create one from the scope/site we are connecting to.
if(passwordPropertyName == null)
passwordPropertyName = getCredentialProperty(authscope);
if(usernamePropertyName == null)
usernamePropertyName = getCredentialProperty(authscope);
// load the password
String pass =
HttpUtilActivator.getCredentialsService().loadPassword(
passwordPropertyName);
// if password is not saved ask user for credentials
if(pass == null)
{
AuthenticationWindow authWindow =
new AuthenticationWindow(authscope.getHost(), true, null);
authWindow.setVisible(true);
if(!authWindow.isCanceled())
{
Credentials cred = new UsernamePasswordCredentials(
authWindow.getUserName(),
new String(authWindow.getPassword())
);
// if password remember is checked lets save passwords,
// if they seem not correct later will be removed.
if(authWindow.isRememberPassword())
{
HttpUtilActivator.getConfigurationService().setProperty(
usernamePropertyName,
authWindow.getUserName());
HttpUtilActivator.getCredentialsService().storePassword(
passwordPropertyName,
new String(authWindow.getPassword())
);
}
return cred;
}
// well user canceled credentials input stop retry asking him
// if credentials are not correct
retry = false;
}
else
{
// we have saved values lets return them
return new UsernamePasswordCredentials(
HttpUtilActivator.getConfigurationService().getString(
usernamePropertyName),
pass);
}
return null;
}
/**
* Clear saved password. Used when we are in situation that
* saved username and password are no longer valid.
*/
public void clear()
{
if(usedScope != null)
{
if(passwordPropertyName == null)
passwordPropertyName = getCredentialProperty(usedScope);
if(usernamePropertyName == null)
usernamePropertyName = getCredentialProperty(usedScope);
HttpUtilActivator.getConfigurationService().removeProperty(
usernamePropertyName);
HttpUtilActivator.getCredentialsService().removePassword(
passwordPropertyName);
}
}
/**
* Constructs property name for save if one is not specified.
* Its in the form
* HTTP_CREDENTIALS_PREFIX.host.realm.port
* @param authscope the scope, holds host,realm, port info about
* the host we are reaching.
* @return return the constructed property.
*/
private static String getCredentialProperty(AuthScope authscope)
{
StringBuilder pref = new StringBuilder();
pref.append(HTTP_CREDENTIALS_PREFIX).append(authscope.getHost())
.append(".").append(authscope.getRealm())
.append(".").append(authscope.getPort());
return pref.toString();
}
/**
* Whether we need to continue retrying.
* @return whether we need to continue retrying.
*/
boolean retry()
{
return retry;
}
}
/**
* Input stream wrapper which handles closing the httpclient when
* everything is retrieved.
*/
private static class HttpClientInputStream
extends InputStream
{
/**
* The original input stream.
*/
InputStream in;
/**
* The http client to close.
*/
HttpClient httpClient;
/**
* Creates HttpClientInputStream.
* @param in the original input stream.
* @param httpClient the http client to close.
*/
HttpClientInputStream(InputStream in, HttpClient httpClient)
{
this.in = in;
this.httpClient = httpClient;
}
/**
* Uses parent InputStream read method.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @throws java.io.IOException if an I/O error occurs.
*/
@Override
public int read()
throws IOException
{
return in.read();
}
/**
* Closes this input stream and releases any system resources associated
* with the stream. Releases httpclient connections.
*
* <p> The <code>close</code> method of <code>InputStream</code> does
* nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void close()
throws IOException
{
super.close();
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate de-allocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}
/**
* Utility class wraps the http requests result and some utility methods
* for retrieving info and content for the result.
*/
public static class HTTPResponseResult
{
/**
* The httpclient entity.
*/
HttpEntity entity;
/**
* The httpclient.
*/
HttpClient httpClient;
/**
* Creates HTTPResponseResult.
* @param entity the httpclient entity.
* @param httpClient the httpclient.
*/
HTTPResponseResult(HttpEntity entity, HttpClient httpClient)
{
this.entity = entity;
this.httpClient = httpClient;
}
/**
* Tells the length of the content, if known.
*
* @return the number of bytes of the content, or
* a negative number if unknown. If the content length is known
* but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE},
* a negative number is returned.
*/
public long getContentLength()
{
return entity.getContentLength();
}
/**
* Returns a content stream of the entity.
*
* @return content stream of the entity.
*
* @throws IOException if the stream could not be created
* @throws IllegalStateException
* if content stream cannot be created.
*/
public InputStream getContent()
throws IOException, IllegalStateException
{
return new HttpClientInputStream(entity.getContent(), httpClient);
}
/**
* Returns a content string of the entity.
*
* @return content string of the entity.
*
* @throws IOException if the stream could not be created
*/
public String getContentString()
throws IOException
{
try
{
return EntityUtils.toString(entity);
}
finally
{
if(httpClient != null)
httpClient.getConnectionManager().shutdown();
}
}
}
}

@ -0,0 +1,71 @@
Bundle-Activator: net.java.sip.communicator.service.httputil.HttpUtilActivator
Bundle-Name: SIP Communicator Http Utility Packages
Bundle-Description: A bundle that export packages with http utility classes.
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
System-Bundle: yes
Import-Package: org.xml.sax,
org.w3c.dom,
org.osgi.framework,
org.apache.xml.serialize,
javax.xml.transform.stream,
javax.xml.transform.dom,
javax.xml.transform,
javax.xml.parsers,
javax.swing.text.html,
javax.swing.text.html.parser,
javax.swing.text,
javax.swing.plaf.basic,
javax.swing.plaf,
javax.swing.plaf.metal,
javax.swing.event,
javax.swing.border,
javax.swing.filechooser,
javax.swing,
javax.naming.directory,
javax.naming,
javax.imageio,
net.java.sip.communicator.util.xml,
net.java.sip.communicator.util,
net.java.sip.communicator.service.resources,
net.java.sip.communicator.service.certificate,
net.java.sip.communicator.service.credentialsstorage,
net.java.sip.communicator.service.keybindings,
net.java.sip.communicator.service.netaddr,
net.java.sip.communicator.service.netaddr.event,
net.java.sip.communicator.service.configuration,
net.java.sip.communicator.service.contactlist,
sun.awt.shell,
sun.net.util,
sun.net.dns,
com.sun.awt,
org.apache.commons.logging,
javax.net.ssl,
javax.security.auth.x500
Export-Package: net.java.sip.communicator.service.httputil,
org.apache.http,
org.apache.http.entity,
org.apache.http.impl,
org.apache.http.impl.entity,
org.apache.http.impl.io,
org.apache.http.io,
org.apache.http.message,
org.apache.http.params,
org.apache.http.protocol,
org.apache.http.util,
org.apache.http.annotation,
org.apache.http.auth,
org.apache.http.auth.params,
org.apache.http.client,
org.apache.http.client.entity,
org.apache.http.client.methods,
org.apache.http.client.params,
org.apache.http.client.protocol,
org.apache.http.client.utils,
org.apache.http.conn,
org.apache.http.conn.params,
org.apache.http.conn.routing,
org.apache.http.conn.scheme,
org.apache.http.conn.ssl,
org.apache.http.conn.util,
org.apache.http.impl.client
Loading…
Cancel
Save