|
Glassfish example source code file (RestUtil.java)
This example Glassfish source code file (RestUtil.java) is included in the DevDaily.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.
The Glassfish RestUtil.java source code
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2009-2011 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.glassfish.admingui.common.util;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.sun.jsftemplating.layout.descriptors.handler.HandlerContext;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.parsers.ParserConfigurationException;
import org.glassfish.admingui.common.security.AdminConsoleAuthModule;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import com.sun.enterprise.security.SecurityServicesUtil;
import com.sun.enterprise.config.serverbeans.SecureAdmin;
import com.sun.enterprise.security.ssl.SSLUtils;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
import org.jvnet.hk2.component.Habitat;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import static org.glassfish.api.ActionReport.ExitCode;
/**
*
* @author anilam
*/
public class RestUtil {
public static final String FORM_ENCODING = "application/x-www-form-urlencoded";
//default to .json instead of .xml
public static final String RESPONSE_TYPE = "application/json";
public static final String GUI_TOKEN_FOR_EMPTY_PROPERTY_VALUE = "()";
public static final Client JERSEY_CLIENT = Client.create();
private static final String REST_TOKEN_COOKIE = "gfresttoken";
public static String getPropValue(String endpoint, String propName, HandlerContext handlerCtx){
Map responseMap = (Map) restRequest(endpoint+"/property.json", null, "GET", handlerCtx, false);
Map extraPropertiesMap = (Map)((Map)responseMap.get("data")).get("extraProperties");
if (extraPropertiesMap != null){
List<Map> props = (List)extraPropertiesMap.get("properties");
for(Map oneProp: props){
if (oneProp.get("name").equals(propName)){
return (String) oneProp.get("value");
}
}
}
return "";
}
public static String resolveToken(String endpoint, String token) {
String tokenStartMarker = "${", tokenEndMarker = "}";
if (!token.trim().startsWith(tokenStartMarker))
return token;
int start = token.indexOf(tokenStartMarker);
if (start < 0)
return token;
int end = token.lastIndexOf(tokenEndMarker);
if (end < 0)
return token;
Map attrMap = new HashMap();
String str = token.substring(start + tokenStartMarker.length(), end - tokenEndMarker.length() + 1);
attrMap.put("tokens", str);
try {
Map result = restRequest(endpoint + "/resolve-tokens.json", attrMap, "GET", null, true);
return (String)GuiUtil.getMapValue(result, "data,extraProperties,tokens," + str);
} catch (Exception ex) {
GuiUtil.getLogger().info(ex.getMessage());
}
return token;
}
public static Map<String, Object> restRequest(String endpoint, Map attrs, String method, HandlerContext handlerCtx, boolean quiet) {
return restRequest(endpoint, attrs, method, handlerCtx, quiet, true);
}
public static Map<String, Object> restRequest(String endpoint, Map attrs, String method, HandlerContext handlerCtx, boolean quiet, boolean throwException) {
boolean useData = false;
Object data = null;
if (attrs == null) {
try {
data = (handlerCtx == null) ? null : handlerCtx.getInputValue("data");
} catch (Exception e) {
//
}
if (data != null) {
// We'll send the raw data
useData = true;
} else {
// Initialize the attributes to an empty map
attrs = new HashMap<String, Object>();
}
}
method = method.toLowerCase();
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST,
GuiUtil.getCommonMessage("LOG_REST_REQUEST_INFO", new Object[]{endpoint, (useData && "post".equals(method))? data: attrs, method}));
}
// Execute the request...
RestResponse response = null;
if ("post".equals(method)) {
if (useData) {
response = post(endpoint, data, (String) handlerCtx.getInputValue("contentType"));
} else {
response = post(endpoint, attrs);
}
} else if ("put".equals(method)) {
response = put(endpoint, attrs);
} else if ("get".equals(method)) {
response = get(endpoint, attrs);
} else if ("delete".equals(method)) {
response = delete(endpoint, attrs);
}
return parseResponse(response, handlerCtx, endpoint, (useData && "post".equals(method))? data: attrs, quiet, throwException);
}
public static Map<String, String> buildDefaultValueMap(String endpoint) throws ParserConfigurationException, SAXException, IOException {
Map<String, String> defaultValues = new HashMap();
RestResponse response = options(endpoint, "application/json");
//System.out.println("=========== response.getResponse():\n " + response.getResponse());
Map<String, Object> data = (Map)response.getResponse().get("data");
List<Map methods = null;
Map<String, Object> extraProperties = (Map) data.get("extraProperties");
methods = (List<Map) extraProperties.get("methods");
for (Map<String, Object> method : methods) {
if ("POST".equals(method.get("name"))) {
Map<String, Object> messageParameters = (Map) method.get("messageParameters");
if (messageParameters != null) {
for (Map.Entry<String, Object> entry : messageParameters.entrySet()) {
String param = entry.getKey();
String defaultValue = (String) ((Map) entry.getValue()).get("defaultValue");
if (!"".equals(defaultValue) && (defaultValue != null)) { // null test necessary?
defaultValues.put(param, defaultValue);
}
}
}
}
}
return defaultValues;
}
public static Map getAttributesMap(String endpoint) {
RestResponse response = get(endpoint);
if (!response.isSuccess()) {
return new HashMap();
}
return getEntityAttrs(endpoint, "entity");
}
public static Map<String, Object> getEntityAttrs(String endpoint, String key) {
Map<String, Object> valueMap = new HashMap();
try {
// Use restRequest to query the endpoint
Map<String, Object> result = restRequest(endpoint, (Map) null, "get", null, false);
int responseCode = (Integer) result.get("responseCode");
if ((responseCode < 200) || (responseCode > 299)) {
throw new RuntimeException((String) result.get("responseBody"));
}
// Pull off the attribute Map
Map<String, Object> data = (Map) result.get("data");
Map<String, Object> extraProperties = (Map) data.get("extraProperties");
if (extraProperties.containsKey(key)) {
valueMap = (Map<String, Object>) extraProperties.get(key);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return valueMap;
}
private static String getMessage(Map aMap){
String message = "";
if (aMap != null){
message = (String) aMap.get("message");
}
return message;
}
public static Map<String, Object> parseResponse(RestResponse response, HandlerContext handlerCtx, String endpoint, Object attrs, boolean quiet, boolean throwException) {
// Parse the response
String message = "";
ExitCode exitCode = ExitCode.FAILURE;
if (response != null) {
try {
int status = response.getResponseCode();
Map responseMap = response.getResponse();
if (responseMap.get("data") != null){
String exitCodeStr = (String)((Map)responseMap.get("data")).get("exit_code");
exitCode = (exitCodeStr != null) ? ExitCode.valueOf(exitCodeStr) : ExitCode.SUCCESS;
}
//Get the message for both WARNING and FAILURE exit_code
if (exitCode != ExitCode.SUCCESS){
Map dataMap = (Map)responseMap.get("data");
if (dataMap != null) {
message = getMessage(dataMap);
if (message == null){
message = "";
}
List<Map> subReports = (List
Other Glassfish examples (source code examples)
Here is a short list of links related to this Glassfish RestUtil.java source code file:
|