Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
   * Other names may be trademarks of their respective owners.
   *
   * 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
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. 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
  * nbbuild/licenses/CDDL-GPL-2-CP.  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. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  * 
  * Contributor(s):
  * 
  * The Original Software is NetBeans. The Initial Developer of the Original
  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
  * Microsystems, Inc. All Rights Reserved.
  * 
  * 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 do not 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.
  */
 package org.netbeans.modules.websvc.saas.codegen.java;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
Code generator for REST services wrapping WSDL-based web service.

Author(s):
nam
 
     
     private JavaSource loginJS;
     private JavaSource callbackJS;
     private JavaSource saasAuthJS;
     private FileObject saasAuthFile;
     private FileObject loginFile;
     private FileObject callbackFile;
     
             Project project) {
         super(beanproject);
    }
    /* 
     * Insert this code before new "+Constants.REST_CONNECTION+"()
     */
    public String getPreAuthenticationCode() {
        String methodBody = "";
        SaasAuthenticationType authType = getBean().getAuthenticationType();
        if (authType == .) {
            methodBody += "        String apiKey = " + getBean().getAuthenticatorClassName() + ".getApiKey();";
        } else if (authType == .) {
            SessionKeyAuthentication sessionKey = (SessionKeyAuthenticationgetBean().getAuthentication();
            methodBody += "        " + getBean().getAuthenticatorClassName() + ".login(" + getLoginArguments() + ");\n";
            List<ParameterInfosignParams = sessionKey.getParameters();
            String paramStr = "";
            if (signParams != null && signParams.size() > 0) {
                paramStr = Util.getSignParamDeclaration(getBean(), signParams, Collections.<ParameterInfo>emptyList());
            }
            String sigName = sessionKey.getSigKeyName();
            paramStr += "        String " +
                    Util.getVariableName(sigName) + " = " +
                    getBean().getAuthenticatorClassName() + ".sign(\n";//sig
            paramStr += "                new String[][] {";
            for (ParameterInfo p : getBean().getInputParameters()) {
                if (p.getName().equals(sigName)) continue;
                
                paramStr += "                    {\"" + p.getName() + "\", " +
                        Util.getVariableName(p.getName()) + "}, ";
            }
            if(getBean().getInputParameters().size() > 0)
                paramStr = paramStr.substring(0, paramStr.length()-2);
            paramStr += "});\n";
            methodBody += paramStr;
        } else if (authType == .) {
            HttpBasicAuthentication httpBasic = (HttpBasicAuthenticationgetBean().getAuthentication();
            methodBody += "        " + getBean().getAuthenticatorClassName() + ".login(" + getLoginArguments() + ");\n";
        }
        return methodBody;
    }
    /* 
     * Insert this code after new "+Constants.REST_CONNECTION+"()
     */
    public String getPostAuthenticationCode() {
        String methodBody = "";
        SaasAuthenticationType authType = getBean().getAuthenticationType();
        if (authType == .) {
            SignedUrlAuthentication signedUrl = (SignedUrlAuthenticationgetBean().getAuthentication();
            List<ParameterInfosignParams = signedUrl.getParameters();
            if (signParams != null && signParams.size() > 0) {
                String paramStr = Util.getSignParamDeclaration(getBean(), signParamsgetBean().getInputParameters());
                paramStr += "        String " +
                        Util.getVariableName(signedUrl.getSigKeyName()) + " = " +
                        getBean().getAuthenticatorClassName() + ".sign(\n";
                paramStr += "                new String[][] {";
                for (ParameterInfo p : signParams) {
                    paramStr += "                    {\"" + p.getName() + "\", " +
                            Util.getVariableName(p.getName()) + "}, ";
                }
                if(getBean().getInputParameters().size() > 0)
                    paramStr = paramStr.substring(0, paramStr.length()-2);
                paramStr += "});\n";
                methodBody += paramStr;
            }
        }
        return methodBody;
    }

    
Create Authenticator
    public void createAuthenticatorClass() throws IOException {
        FileObject targetFolder = getSaasServiceFolder();
        if(!getBean().isUseTemplates()) {
            if( == null) {
                String authFileName = getBean().getAuthenticatorClassName();
                String authTemplate = null;
                SaasAuthenticationType authType = getBean().getAuthenticationType();
                if (authType == .) {
                    authTemplate = . + 
                            getAuthenticationType().getClassIdentifier();
                } else if (authType == .) {
                    authTemplate = . + 
                            getAuthenticationType().getClassIdentifier();
                } else if (authType == .) {
                    authTemplate = . + 
                            getAuthenticationType().getClassIdentifier();
                } else if (authType == .) {
                    authTemplate = . + 
                            getAuthenticationType().getClassIdentifier();
                }
                if (authTemplate != null) {
                     = JavaSourceHelper.createJavaSource(
                            authTemplate + . + "."+.,
                            targetFoldergetBean().getSaasServicePackageName(), authFileName);// NOI18n
                    Set<FileObjectfiles = new HashSet<FileObject>(.getFileObjects());
                    if (files != null && files.size() > 0) {
                         = files.iterator().next();
                    }
                }
            }
        } else {
            UseTemplates useTemplates = null;
            if(getBean().getAuthentication() instanceof SessionKeyAuthentication) {
                SessionKeyAuthentication sessionKey = (SessionKeyAuthenticationgetBean().getAuthentication();
                useTemplates = sessionKey.getUseTemplates();
            } else if(getBean().getAuthentication() instanceof HttpBasicAuthentication) {
                HttpBasicAuthentication httpBasic = (HttpBasicAuthenticationgetBean().getAuthentication();
                useTemplates = httpBasic.getUseTemplates();
            }
            if(useTemplates != null) {
                for (Template template : useTemplates.getTemplates()) {
                    if(!template.getDropTypeList().contains(getDropFileType().prefix()))
                        continue;
                    
                    String id = template.getId();
                    String type = template.getType();
                    String templateUrl = template.getUrl();
                  
                     //FIXME - Hack
                    if(!templateUrl.contains("Desktop"))
                        continue;
                    String fileName = null;
                    
//                    if (type.equals(Constants.AUTH)) {
                    if(templateUrl.contains("Authenticator")) {
                        fileName = getBean().getAuthenticatorClassName();
                    } else
                        continue;
                    if(templateUrl.endsWith("."+.)) {
                        JavaSourceHelper.createJavaSource(templateUrltargetFolder
                                getBean().getSaasServicePackageName(), fileName);
                    } else {
                        if (templateUrl.indexOf("/") != -1) {
                            fileName = getBean().getSaasName() +
                                    templateUrl.substring(templateUrl.lastIndexOf("/") + 1);
                        }
                        if (fileName != null) {
                            FileObject fobj = targetFolder.getFileObject(fileName);
                            if (fobj == null) {
                                Util.createDataObjectFromTemplate(templateUrltargetFolder,
                                        fileName);
                            }
                        }
                    }
                }
            }
        }
        //Also copy profile.properties
            String profileName = getBean().getAuthenticatorClassName().toLowerCase();
            if (getAuthenticationProfile() != null && !getAuthenticationProfile().trim().equals("")) {
                try {
                    Util.createDataObjectFromTemplate(getAuthenticationProfile(),
                            targetFolderprofileName);
                } catch (Exception ex) {
                    throw new IOException("Profile file specified in " +
                            "saas-services/service-metadata/authentication/@profile, " +
                            "not found: " + getAuthenticationProfile());// NOI18n
                }
            }
        }
    }

    
    
Create Authorization Frame
    public void createAuthorizationClasses() throws IOException {
    }

    
Return target and generated file objects
    public void modifyAuthenticationClass() throws IOException {
            return;
        }
        Modifier[] modifiers = .;
        Object[] throwList = null;
        if (sessionKey.getUseGenerator() != null) {
            UseGenerator useGenerator = sessionKey.getUseGenerator();
            //create getSessionKey() method
            String methodName = "getSessionKey";
            String comment = "";
            String bodyText = "";
            Object returnType = null;
            if (sessionKey.getSessionKeyName() != null) {
                String name = Util.getParameterName(sessionKey.getSessionKeyName(), truetrue);
                List<ParameterInfofields = new ArrayList<ParameterInfo>();
                fields.add(new ParameterInfo(nameString.class));
                Modifier[] modifier = .;
                JavaUtil.addInputParamFields(fieldsmodifier);//add sessionKey field. apiKey, secret fields already in template
                methodName = Util.getSessionKeyMethodName(name);
                comment = methodName + "\n";
                returnType = "String";
                bodyText = "return " + name + ";\n";
                if (bodyText != null) {
                    modifyAuthenticationClass(commentmodifiersreturnTypemethodName,
                            nullnullthrowListbodyText);
                }
            }
            //create login() method
            returnType = .;
            methodName = .;
            comment = methodName + "\n";
            List<ParameterInfofilterParams = getAuthenticatorMethodParameters();
            final String[] parameters = Util.getGetParamNames(filterParams);
            final Object[] paramTypes = Util.getGetParamTypes(filterParams);
            bodyText = getLoginBody(getBean(), getBean().getDisplayName(), .);
            if (bodyText != null) {
                modifyAuthenticationClass(commentmodifiersreturnTypemethodName,
                        parametersparamTypesthrowListbodyText);
            }
            //create getToken() method
            methodName = Util.getTokenMethodName(useGenerator);
            comment = methodName + "\n";
            returnType = "String";
            bodyText = getTokenBody(getBean(), getBean().getDisplayName(), .,
                    getBean().getSaasServicePackageName());
            if (bodyText != null) {
                modifyAuthenticationClass(commentmodifiersreturnTypemethodName,
                        parametersparamTypesthrowListbodyText);
            }
            //create logout() method
            methodName = "logout";
            comment = methodName + "\n";
            returnType = .;
            bodyText = getLogoutBody();
            if (bodyText != null) {
                modifyAuthenticationClass(commentmodifiersreturnTypemethodName,
                        parametersparamTypesthrowListbodyText);
            }
        }
    }

    
Return target and generated file objects
    public void modifyAuthenticationClass(final String commentfinal Object[] modifiers,
            final Object returnTypefinal String namefinal String[] parametersfinal Object[] paramTypes,
            final Object[] throwListfinal String bodyText)
            throws IOException {
        if (JavaSourceHelper.isContainsMethod(nameparametersparamTypes)) {
            return;
        }
            public void run(WorkingCopy copythrows IOException {
                copy.toPhase(..);
                ClassTree initial = JavaSourceHelper.getTopLevelClassTree(copy);
                ClassTree tree = JavaSourceHelper.addMethod(copyinitial,
                        (Modifier[])modifiersnullnull,
                        namereturnTypeparametersparamTypes,
                        nullnull,
                        throwList"{ \n" + bodyText + "\n }"comment);
                copy.rewrite(initialtree);
            }
        });
        result.commit();
    }
    public String getLoginBody(SaasBean bean,
            String groupNameString paramVariableNamethrows IOException {
        if (getBean().isDropTargetWeb()) {
            if (getBean().getAuthenticationType() != .) {
                return null;
            }
            return Util.createSessionKeyLoginBodyForWeb(beangroupNameparamVariableName);
        }
        String methodBody = "";
        UseGenerator useGenerator = sessionKey.getUseGenerator();
        if (useGenerator != null) {
            Login login = useGenerator.getLogin();
            if (login != null) {
                String tokenName = Util.getTokenName(useGenerator);
                String tokenMethodName = Util.getTokenMethodName(useGenerator);
                methodBody += "        if (" + Util.getVariableName(sessionKey.getSessionKeyName()) + " == null) {\n";
                methodBody += "            String " + tokenName + " = " + tokenMethodName + "(" +
                        Util.getHeaderOrParameterUsage(getAuthenticatorMethodParameters()) + ");\n\n";
                methodBody += "            if (" + tokenName + " != null) {\n";
                methodBody += "                try {\n";
                Map<StringStringtokenMap = new HashMap<StringString>();
                methodBody += Util.getLoginBody(logingetBean(), groupNametokenMap);
                methodBody += "                } catch (IOException ex) {\n";
                methodBody += "                    Logger.getLogger(" + getBean().getAuthenticatorClassName() + ".class.getName()).log(Level.SEVERE, null, ex);\n";
                methodBody += "                }\n\n";
                methodBody += "            }\n";
                methodBody += "        }\n";
            }
        }
        return methodBody;
    }
    public String getLogoutBody() {
        String methodBody = "";
        return methodBody;
    }
    public String getTokenBody(SaasBean bean,
            String groupNameString paramVariableNameString saasServicePkgNamethrows IOException {
        if (getBean().isDropTargetWeb()) {
            if (getBean().getAuthenticationType() != .) {
                return null;
            }
            return Util.createSessionKeyTokenBodyForWeb(beangroupNameparamVariableName,
                    saasServicePkgName);
        }
        String authFileName = getBean().getAuthorizationFrameClassName();
        String methodBody = "";
        UseGenerator useGenerator = sessionKey.getUseGenerator();
        if (useGenerator != null) {
            Token token = useGenerator.getToken();
            if (token != null) {
                String tokenName = Util.getTokenName(useGenerator);
                String sigId = "sig";
                if (token.getSignId() != null) {
                    sigId = token.getSignId();
                }
                String methodName = null;
                Method method = token.getMethod();
                if (method != null) {
                    methodName = method.getHref();
                    if (methodName == null) {
                        return methodBody;
                    } else {
                        methodName = methodName.startsWith("#") ? methodName.substring(1) : methodName;
                    }
                }
                methodBody += "       String " + tokenName + " = null;\n";
                methodBody += "       try {\n";
                methodBody += "            String method = \"" + methodName + "\";\n";
                methodBody += "            String v = \"1.0\";\n\n";
                List<ParameterInfosignParams = token.getParameters();
                if (signParams != null && signParams.size() > 0) {
                    String paramStr = "";
                    paramStr += "        String " + sigId + " = sign(secret, \n";
                    paramStr += getSignParamUsage(signParamsgroupName);
                    paramStr += ");\n\n";
                    methodBody += paramStr;
                }
                String queryParamsCode = "";
                Map<StringStringtokenMap = new HashMap<StringString>();
                if (method != null) {
                    String id = method.getId();
                    if (id != null) {
                        String[] tokens = id.split(",");
                        for (String tk : tokens) {
                            String[] tokenElem = tk.split("=");
                            if (tokenElem.length == 2) {
                                tokenMap.put(tokenElem[0], tokenElem[1]);
                            }
                        }
                    }
                    String href = method.getHref();
                    if (href != null && bean instanceof RestClientSaasBean) {
                        org.netbeans.modules.websvc.saas.model.wadl.Method wadlMethod =
                                SaasUtil.wadlMethodFromIdRef(
                                ((RestClientSaasBean)bean).getMethod().getSaas().getWadlModel(), href);
                        if (wadlMethod != null) {
                            ArrayList<ParameterInfoparams = ((RestClientSaasBean)bean).findWadlParams(wadlMethod);
                            if (params != null &&
                                    params.size() > 0) {
                                queryParamsCode = Util.getHeaderOrParameterDefinition(paramsparamVariableNamefalse);
                            }
                        }
                    }
                }
                //Insert parameter declaration
                methodBody += "        " + queryParamsCode;
                String url = "";
                if (bean instanceof RestClientSaasBean) {
                    url = ((RestClientSaasBeanbean).getUrl();
                }
                methodBody += "             " + . + " conn = new " + . + "(\"" + url + "\"";
                if (!queryParamsCode.trim().equals("")) {
                    methodBody += ", " + paramVariableName;
                }
                methodBody += ");\n";
                methodBody += "            String result = conn.get();\n";
                for (Entry e : tokenMap.entrySet()) {
                    String name = Util.getVariableName((Stringe.getKey());
                    String val = (Stringe.getValue();
                    if (val.startsWith("{")) {
                        val = val.substring(1);
                    }
                    if (val.endsWith("}")) {
                        val = val.substring(0, val.length() - 1);
                    }
                    methodBody += "            " + name + " = result.substring(result.indexOf(\"<" + val + "\"),\n";
                    methodBody += "                            result.indexOf(\"</" + val + ">\"));\n\n";
                    methodBody += "            " + name + " = " + name + ".substring(" + name + ".indexOf(\">\") + 1);\n\n";
                }
                if (token.getPrompt() != null) {
                    Prompt prompt = token.getPrompt();
                    signParams = prompt.getParameters();
                    if (signParams != null && signParams.size() > 0) {
                        methodBody += "            String perms = \"write\";";
                        String paramStr = "";
                        paramStr += "        " + sigId + " = sign(\n";
                        paramStr += "                new String[][] {\n";
                        for (ParameterInfo p : signParams) {
                            paramStr += "                    {\"" + p.getName() + "\", " +
                                    Util.getParameterName(ptruetrue) + "},\n";
                        }
                        paramStr += "        });\n\n";
                        methodBody += paramStr;
                    }
                    url = prompt.getDesktopUrl();
                    methodBody += "            String loginUrl = \"" + Util.getTokenPromptUrl(tokenurl) + "\";\n";
                }
                methodBody += "            " + authFileName + " frame = new " + authFileName + "(loginUrl);\n";
                methodBody += "            synchronized (frame) {\n";
                methodBody += "                try {\n";
                methodBody += "                    frame.wait();\n";
                methodBody += "                } catch (InterruptedException ex) {\n";
                methodBody += "                    Logger.getLogger(" + getBean().getAuthenticatorClassName() + ".class.getName()).log(Level.SEVERE, null, ex);\n";
                methodBody += "                }\n";
                methodBody += "            }\n";
                methodBody += "       } catch (IOException ex) {\n";
                methodBody += "            Logger.getLogger(" + getBean().getAuthenticatorClassName() + ".class.getName()).log(Level.SEVERE, null, ex);\n";
                methodBody += "       }\n\n";
                methodBody += "       return " + tokenName + ";\n";
            }
        }
        return methodBody;
    }
    public String getSignParamUsage(List<ParameterInfosignParamsString groupName) {
        return Util.getSignParamUsage(signParamsgroupName
                getBean().isDropTargetWeb());
    }
New to GrepCode? Check out our FAQ X