use of java.net.MalformedURLException in project OpenAM by OpenRock.
the class AuthClientUtils method sendAuthRequestToOrigServer.
/**
* Sends the request to the original Auth server and receives the result
* data.
*
* @param request HttpServletRequest to be sent
* @param response HttpServletResponse to be received
* @param cookieURL URL of the original authentication server to be
* connected
*
* @return HashMap of the result data from the original server's response
*
*/
public static Map<String, Object> sendAuthRequestToOrigServer(HttpServletRequest request, HttpServletResponse response, String cookieURL) {
Map<String, Object> origRequestData = new HashMap<String, Object>();
// Print request Headers
if (utilDebug.messageEnabled()) {
StringBuilder message = new StringBuilder();
Enumeration<String> requestHeaders = request.getHeaderNames();
while (requestHeaders.hasMoreElements()) {
String name = requestHeaders.nextElement();
Enumeration value = (Enumeration) request.getHeaders(name);
message.append("Header name='").append(name).append("', Value='").append(value).append("'\n");
}
utilDebug.message(message.toString());
}
// Open URL connection
HttpURLConnection conn = null;
OutputStream out = null;
String strCookies = null;
URL authURL = null;
try {
String queryString = request.getQueryString();
if (queryString != null) {
authURL = new URL(cookieURL + "?" + queryString);
} else {
authURL = new URL(cookieURL);
}
if (utilDebug.messageEnabled()) {
utilDebug.message("Connecting to : " + authURL);
}
conn = HttpURLConnectionManager.getConnection(authURL);
conn.setUseCaches(useCache);
conn.setFollowRedirects(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty(ISAuthConstants.ACCEPT_LANG_HEADER, request.getHeader(ISAuthConstants.ACCEPT_LANG_HEADER));
// We should preserve the original host, so the target server will also see the accessed URL
// If we don't do this the server might going to deny the request because of invalid domain access.
conn.setRequestProperty("Host", request.getHeader("host"));
List<Cookie> cookies = removeLocalLoadBalancingCookie(asList(request.getCookies()));
// replay cookies
strCookies = getCookiesString(cookies);
if (strCookies != null) {
if (utilDebug.messageEnabled()) {
utilDebug.message("Sending cookies : " + strCookies);
}
conn.setRequestProperty("Cookie", strCookies);
}
// Sending Output to Original Auth server...
utilDebug.message("SENDING DATA ... ");
copyRequestHeaders(request, conn);
if (request.getMethod().equals("GET")) {
conn.connect();
} else {
//First we should find out what GET parameters do we have.
Map<String, Set<String>> queryParams = new HashMap<String, Set<String>>();
if (queryString != null) {
for (String param : queryString.split("&")) {
int idx = param.indexOf('=');
if (idx != -1) {
String paramName = param.substring(0, idx);
String paramValue = param.substring(idx + 1);
Set<String> values = queryParams.get(paramName);
if (values == null) {
values = new HashSet<String>();
queryParams.put(paramName, values);
}
values.add(paramValue);
}
}
}
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// merged parameter list containing both GET and POST parameters
Map<String, String[]> params = request.getParameterMap();
Map<String, Set<String>> postParams = new HashMap<String, Set<String>>();
for (Map.Entry<String, String[]> entry : params.entrySet()) {
if (queryParams.containsKey(entry.getKey())) {
// TODO: do we need to care about params that can be both in GET and POST?
} else {
postParams.put(entry.getKey(), new HashSet<String>(asList(entry.getValue())));
}
}
String postData = getFormData(postParams);
if (utilDebug.messageEnabled()) {
utilDebug.message("Request data : " + postData);
}
if (postData.trim().length() > 0) {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
out = conn.getOutputStream();
PrintWriter pw = new PrintWriter(out);
// here we "send" the request body
pw.print(postData);
pw.flush();
pw.close();
}
}
// Receiving input from Original Auth server...
utilDebug.message("RECEIVING DATA ... ");
if (utilDebug.messageEnabled()) {
utilDebug.message("Response Code='{}', Response Message='{}' ", conn.getResponseCode(), conn.getResponseMessage());
}
// Check response code
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Input from Original servlet...
StringBuilder in_buf = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
int len;
char[] buf = new char[1024];
while ((len = in.read(buf, 0, buf.length)) != -1) {
in_buf.append(buf, 0, len);
}
String in_string = in_buf.toString();
if (utilDebug.messageEnabled()) {
utilDebug.message("Received response data : " + in_string);
}
origRequestData.put("OUTPUT_DATA", in_string);
} else {
utilDebug.warning("Response code for proxied auth is NOT OK");
}
String client_type = conn.getHeaderField("AM_CLIENT_TYPE");
if (client_type != null) {
origRequestData.put("AM_CLIENT_TYPE", client_type);
}
String redirect_url = conn.getHeaderField("Location");
if (redirect_url != null) {
try {
URL gotoURL = new URL(redirect_url);
if (isSameServer(authURL, gotoURL)) {
if (utilDebug.messageEnabled()) {
utilDebug.message("Relative redirect detected");
}
//relative redirect happened
String path = gotoURL.getPath();
String query = gotoURL.getQuery();
redirect_url = (path != null ? path : "") + (query != null ? "?" + gotoURL.getQuery() : "");
}
if (utilDebug.messageEnabled()) {
utilDebug.message("sendAuthRequestToOrigServer(): Setting redirect URL to: " + redirect_url);
}
origRequestData.put("AM_REDIRECT_URL", redirect_url);
} catch (MalformedURLException murle) {
//fallback to original handling
origRequestData.put("AM_REDIRECT_URL", redirect_url);
}
}
String content_type = conn.getHeaderField("Content-Type");
if (content_type != null) {
origRequestData.put("CONTENT_TYPE", content_type);
}
origRequestData.put("RESPONSE_CODE", conn.getResponseCode());
//replay received headers to the original response
copyResponseHeaders(conn.getHeaderFields(), response);
} catch (IOException ioe) {
//the catcher will log the exception
origRequestData.put("EXCEPTION", ioe);
} catch (Exception e) {
if (utilDebug.warningEnabled()) {
utilDebug.warning("send exception : ", e);
}
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
if (utilDebug.messageEnabled()) {
utilDebug.message("send IOException : ", ioe);
}
}
}
}
return origRequestData;
}
use of java.net.MalformedURLException in project OpenAM by OpenRock.
the class TaskModelImpl method getConfigureGoogleAppsURLs.
public Map getConfigureGoogleAppsURLs(String realm, String entityId) throws AMConsoleException {
Map map = new HashMap();
IDPSSODescriptorElement idpssoDescriptor = null;
try {
SAML2MetaManager samlManager = new SAML2MetaManager();
idpssoDescriptor = samlManager.getIDPSSODescriptor(realm, entityId);
String signinPageURL = null;
if (idpssoDescriptor != null) {
List signonList = idpssoDescriptor.getSingleSignOnService();
for (int i = 0; i < signonList.size(); i++) {
SingleSignOnServiceElement signElem = (SingleSignOnServiceElement) signonList.get(i);
String tmp = signElem.getBinding();
if (tmp.contains("HTTP-Redirect")) {
signinPageURL = signElem.getLocation();
map.put("SigninPageURL", returnEmptySetIfValueIsNull(signinPageURL));
}
}
}
URL aURL = new URL(signinPageURL);
String signoutPageURL = null;
String protocol = aURL.getProtocol();
String host = aURL.getHost();
int port = aURL.getPort();
if (port == -1) {
port = (aURL.getProtocol().equals("https")) ? 443 : 80;
}
String deploymentURI = SystemPropertiesManager.get(Constants.AM_SERVICES_DEPLOYMENT_DESCRIPTOR);
String url = protocol + "://" + host + ":" + port + deploymentURI;
signoutPageURL = url + "/UI/Logout?goto=" + url;
map.put("SignoutPageURL", returnEmptySetIfValueIsNull(signoutPageURL));
map.put("ChangePasswordURL", returnEmptySetIfValueIsNull(url + "/idm/EndUser"));
// get pubkey
Map extValueMap = new HashMap();
IDPSSOConfigElement idpssoConfig = samlManager.getIDPSSOConfig(realm, entityId);
if (idpssoConfig != null) {
BaseConfigType baseConfig = (BaseConfigType) idpssoConfig;
extValueMap = SAML2MetaUtils.getAttributes(baseConfig);
}
List aList = (List) extValueMap.get("signingCertAlias");
String signingCertAlias = null;
if (aList != null) {
signingCertAlias = (String) aList.get(0);
}
String publickey = SAML2MetaSecurityUtils.buildX509Certificate(signingCertAlias);
String str = "-----BEGIN CERTIFICATE-----\n" + publickey + "-----END CERTIFICATE-----\n";
map.put("PubKey", returnEmptySetIfValueIsNull(str));
} catch (SAML2MetaException ex) {
throw new AMConsoleException(ex.getMessage());
} catch (MalformedURLException ex) {
throw new AMConsoleException(ex.getMessage());
}
return map;
}
use of java.net.MalformedURLException in project OpenAM by OpenRock.
the class IdentityServicesImpl method createAgent.
/**
* To be backward compatible, look for 'AgentType' attribute
* in the attribute map which is passed as a parameter and if
* not present/sent, check if the IdType.AGENTONLY or AGENT
* and then assume that it is '2.2_Agent' type to create
* that agent under the 2.2_Agent node.
**/
private void createAgent(Map<String, Set<String>> idAttrs, IdType objectIdType, String idType, String idName, String realm, SSOToken adminToken) throws SMSException, SSOException, ConfigurationException, IdRepoException, MalformedURLException {
String agentType;
String serverUrl = null;
String agentUrl = null;
final String SERVER_URL = "serverurl";
final String AGENT_URL = "agenturl";
final String DEFAULT_AGENT_TYPE = "2.2_Agent";
Set<String> set = idAttrs.remove(IdConstants.AGENT_TYPE);
if (set == null) {
set = idAttrs.remove(AGENT_TYPE_LOWER_CASE);
}
if (set != null && !set.isEmpty()) {
agentType = set.iterator().next();
} else if (objectIdType.equals(IdType.AGENTONLY) || objectIdType.equals(IdType.AGENT)) {
agentType = DEFAULT_AGENT_TYPE;
} else {
throw new UnsupportedOperationException("Unsupported: Agent Type required for " + idType);
}
set = idAttrs.remove(SERVER_URL);
if (set != null && !set.isEmpty()) {
serverUrl = set.iterator().next();
}
set = idAttrs.remove(AGENT_URL);
if (set != null && !set.isEmpty()) {
agentUrl = set.iterator().next();
}
if (agentType.equals(AgentConfiguration.AGENT_TYPE_WEB) || agentType.equals(AgentConfiguration.AGENT_TYPE_J2EE)) {
if (StringUtils.isBlank(agentUrl)) {
throw new MalformedURLException("Agent type requires agenturl to be configured.");
} else if (StringUtils.isBlank(serverUrl)) {
throw new MalformedURLException("Agent type requires serverurl to be configured.");
}
}
if (objectIdType.equals(IdType.AGENT) || objectIdType.equals(IdType.AGENTONLY)) {
if (StringUtils.isBlank(serverUrl) || StringUtils.isBlank(agentUrl)) {
AgentConfiguration.createAgent(adminToken, realm, idName, agentType, idAttrs);
} else {
AgentConfiguration.createAgent(adminToken, realm, idName, agentType, idAttrs, serverUrl, agentUrl);
}
} else {
if (StringUtils.isBlank(serverUrl) || StringUtils.isBlank(agentUrl)) {
AgentConfiguration.createAgentGroup(adminToken, realm, idName, agentType, idAttrs);
} else {
AgentConfiguration.createAgentGroup(adminToken, realm, idName, agentType, idAttrs, serverUrl, agentUrl);
}
}
}
use of java.net.MalformedURLException in project OpenAM by OpenRock.
the class NormalizedURL method normalize.
/**
* Returns a normalized URL object.
*
* @param strURL String representation of the URL.
*/
public static String normalize(String strURL) {
URL url = null;
try {
url = new URL(strURL);
} catch (MalformedURLException e) {
// cannot be normalized
return strURL;
}
String protocol = url.getProtocol();
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
String sPort;
if (port == -1) {
sPort = protocol.equals("https") ? "443" : "80";
} else {
sPort = Integer.toString(port);
}
return protocol + "://" + host + ":" + sPort + path;
}
use of java.net.MalformedURLException in project pcgen by PCGen.
the class LstFileLoader method readFromURI.
/**
* This method reads the given URL and stores its contents in the provided
* data buffer, returning a URL to the specified file for use in log/error
* messages by its caller.
*
* @param uri String path of the URL to read -- MUST be a URL path,
* not a file!
* @return URL pointing to the actual file read, for use in debug/log
* messages
* @throws PersistenceLayerException
*/
public static StringBuilder readFromURI(URI uri) throws PersistenceLayerException {
if (uri == null) {
// We have a problem!
throw new PersistenceLayerException("LstFileLoader.readFromURI() received a null uri parameter!");
}
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
throw new PersistenceLayerException("LstFileLoader.readFromURI() could not convert parameter to a URL: " + e.getLocalizedMessage());
}
InputStream inputStream = null;
StringBuilder dataBuffer = null;
try {
//only load local urls, unless loading of URLs is allowed
if (!CoreUtility.isNetURL(url) || SettingsHandler.isLoadURLs()) {
// try to make a buffer of sufficient size in one go to save on GC
int size = 2048;
if ("file".equals(url.getProtocol())) {
long fileSize = new File(url.getPath()).length();
if (fileSize > 0) {
// this is an overestimate if the LST has wide
// characters, but it's accurate for ASCII
size = (int) fileSize;
}
}
dataBuffer = new StringBuilder(size);
// Get the URL and open the stream
inputStream = url.openStream();
// Read from the stream
final InputStreamReader ir = //$NON-NLS-1$
new InputStreamReader(inputStream, "UTF-8");
// Buffer the stream content
final char[] b = new char[512];
int n;
n = ir.read(b, 0, 1);
/*
* Take out the optional BOM: This is a pre-Java 1.6 workaround
* for Sun B-U-G 4508058, see:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
*/
if (n == 1 && b[0] != '') {
dataBuffer.append(b, 0, 1);
}
while ((n = ir.read(b)) > 0) {
dataBuffer.append(b, 0, n);
}
} else {
// Just to protect people from using web
// sources without their knowledge,
// we added a preference.
ShowMessageDelegate.showMessageDialog("Preferences are currently set to NOT allow\nloading of " + "sources from web links. \n" + url + " is a web link", Constants.APPLICATION_NAME, MessageType.ERROR);
// aURL = null; //currently unnecessary reassignment
}
} catch (IOException ioe) {
// Don't throw an exception here because a simple
// file not found will prevent ANY other files from
// being loaded/processed -- NOT what we want
Logging.errorPrint("ERROR:" + url + "\n" + "Exception type:" + ioe.getClass().getName() + "\n" + "Message:" + ioe.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e2) {
Logging.errorPrint("Can't close inputStream in LstSystemLoader.initFile", e2);
}
}
}
return dataBuffer == null ? new StringBuilder() : dataBuffer;
}
Aggregations