Example usage for java.net URISyntaxException toString

List of usage examples for java.net URISyntaxException toString

Introduction

In this page you can find the example usage for java.net URISyntaxException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.apache.stratos.cloud.controller.iaases.vcloud.VCloudIaas.java

@Override
public String attachVolume(String instanceId, String volumeId, String deviceName) {
    IaasProvider iaasInfo = getIaasProvider();

    if (StringUtils.isEmpty(volumeId)) {
        log.error("Volume provided to attach can not be null");
    }//  w  w  w  .j  a  v  a2 s  .  c  om

    if (StringUtils.isEmpty(instanceId)) {
        log.error("Instance provided to attach can not be null");
    }

    URI instanceIdHref = null;
    URI volumeIdHref = null;
    try {
        //the instanceId format is a bit silly for vCloud.
        instanceIdHref = new URI("https:/" + instanceId);
    } catch (URISyntaxException e) {
        log.error(
                "Failed to attach volume, because the instance id cannot be converted into a url by concatenating "
                        + "'https:/' with " + instanceId + ". Full stacktrace: " + e.toString());
        return null;
    }
    try {
        volumeIdHref = new URI(volumeId);
    } catch (URISyntaxException e) {
        log.error("Failed to attach voluume, because the volume id '" + volumeId
                + "' is not a valid href (URI))" + e.toString());
    }

    //get 'native' version of jclouds' vCloud API.
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();

    VCloudApi api = context.unwrapApi(VCloudApi.class);

    //Disks need to be attached to individual VMs, not vApps. The instanceId is the VApp.
    VAppApi vAppApi = api.getVAppApi();
    Set<Vm> vmsInVapp = vAppApi.getVApp(instanceIdHref).getChildren();
    //Each vApp today has just 1 VM in it. Validate assumption.
    assert (vmsInVapp.size() == 1);
    Vm vm = vmsInVapp.iterator().next();
    URI vmHref = vm.getHref();
    VmApi vmApi = api.getVmApi();

    // invest
    /*
    VCloudHardDisk.Builder hardDiskBuilder = new VCloudHardDisk.Builder();
    VCloudHardDisk hardDisk = hardDiskBuilder.instanceID(volumeId).build();
    VCloudVirtualHardwareSection vvhs = vm.getVirtualHardwareSection();
    VCloudHardDisk.Builder Vchd = new VCloudHardDisk.Builder();
    vvhs.toBuilder().item(Vchd.capacity(3).instanceID("hgfhgf").build()).build();
    VApp va = vAppApi.getVApp(instanceIdHref);
            
    */ //EO invest
    DiskAttachOrDetachParams params = new DiskAttachOrDetachParams(volumeIdHref);
    Task t = vmApi.attachDisk(vmHref, params);

    log.info(String.format(
            "Volume [id]: %s attachment for instance [id]: %s was successful [status]: Attaching. Iaas : %s, Task: %s",
            volumeId, instanceId, iaasInfo, t));
    return "Attaching";
}

From source file:org.nimbustools.messaging.gt4_0_elastic.v2008_05_05.rm.defaults.DefaultRun.java

public CreateRequest translateRunInstances(RunInstancesType req, Caller caller)
        throws RemoteException, CannotTranslateException {

    final String ownerID;
    try {/*ww w  .j a  va2  s .com*/
        ownerID = this.container.getOwnerID(caller);
    } catch (CannotTranslateException e) {
        throw new RemoteException(e.getMessage(), e);
    }

    final String imageID = req.getImageId();
    if (imageID == null) {
        throw new RemoteException("Request is missing image ID");
    }

    // currently ignored: groupSet, placement, kernel, ramdiskid,
    // blockDeviceMapping

    final _CustomizationRequest cust;
    final String keyname = req.getKeyName();
    if (keyname != null && this.sshKeys != null) {
        cust = this.repr._newCustomizationRequest();
        final SSHKey key = this.sshKeys.findKey(ownerID, keyname);
        if (key == null) {
            throw new RemoteException("There is no key '" + keyname + "' registered for you to use");
        }
        cust.setContent(key.getPubKeyValue());
        cust.setPathOnVM("/root/.ssh/authorized_keys");
    } else {
        cust = null;
    }

    final CustomizationRequest[] custRequests;
    if (cust != null) {
        custRequests = new CustomizationRequest[1];
        custRequests[0] = cust;
    } else {
        custRequests = null;
    }

    final String raType = req.getInstanceType();
    final ResourceAllocation ra = this.RAs.getMatchingRA(raType, req.getMinCount(), req.getMaxCount(), false);
    final NIC[] nics = this.getNICs(ra.getPublicNetwork(), ra.getPrivateNetwork());
    final RequiredVMM reqVMM = this.RAs.getRequiredVMM();

    String userData = null;
    final UserDataType t_userData = req.getUserData();
    if (t_userData != null) {
        final String base64Encoded = t_userData.getData();
        if (base64Encoded != null) {
            // Remove newlines from the base64 string since they are not
            // supported by the Globus implementation
            final String base64EncodedNoCRLF = base64Encoded.replaceAll("[\r\n]", "");
            if (!Base64.isBase64(base64EncodedNoCRLF)) {
                throw new RemoteException("userdata does not appear to " + "be base64 encoded?");
            }
            final byte[] bytes = Base64.decode(base64EncodedNoCRLF.getBytes());
            userData = new String(bytes);
        }
    }

    final VMFile[] files = this.repository.constructFileRequest(imageID, ra, caller);

    final String clientToken = req.getClientToken();

    String availabilityZone = null;
    if (req.getPlacement() != null) {
        availabilityZone = req.getPlacement().getAvailabilityZone();
    }

    final _CreateRequest creq = this.repr._newCreateRequest();

    DefaultKernel kernel = null;
    String kernelRequestString = req.getKernelId();
    if (kernelRequestString != null) {
        kernel = new DefaultKernel();
        try {
            URI kernelURI = new URI("file://" + kernelRequestString);
            kernel.setKernel(kernelURI);
        } catch (URISyntaxException ueie) {
            throw new RemoteException(ueie.toString());
        }
    }

    creq.setContext(null);
    creq.setCoScheduleDone(false);
    creq.setCoScheduleID(null);
    creq.setCoScheduleMember(false);
    creq.setCustomizationRequests(custRequests);
    creq.setInitialStateRequest(State.STATE_Running);
    creq.setName(imageID);
    creq.setRequestedKernel(kernel); // todo
    creq.setRequestedNics(nics);
    creq.setRequestedRA(ra);
    creq.setRequestedSchedule(null); // ask for default
    creq.setRequiredVMM(reqVMM);
    creq.setShutdownType(CreateRequest.SHUTDOWN_TYPE_TRASH);
    creq.setVMFiles(files);
    creq.setMdUserData(userData);
    creq.setSshKeyName(keyname);
    creq.setClientToken(clientToken);
    creq.setRequestedResourcePool(availabilityZone);

    return creq;
}

From source file:com.grendelscan.ui.http.transactionDisplay.TransactionComposite.java

public void displayTransactionData(final StandardHttpTransaction transaction) {
    getShell().setText(GrendelScan.versionText + " - Transaction " + transaction.getId());
    byte[] request = transaction.getRequestWrapper().getBytes();
    byte[] response = new byte[0];
    if (showResponse && transaction.isResponsePresent()) {
        response = transaction.getResponseWrapper().getBytes();
    }/*from  ww w. j  a v a  2  s . c o  m*/
    try {
        updateTransactionData(request, response);
    } catch (URISyntaxException e) {
        IllegalStateException ise = new IllegalStateException("Really, really weird problem with uri parsing",
                e);
        LOGGER.error(e.toString(), e);
        throw ise;
    }
}

From source file:com.cloud.hypervisor.xen.resource.XenServerStorageResource.java

protected Answer execute(CopyCmd cmd) {
    DecodedDataObject srcObj = null;/*  w  ww  .j  a  va2s. com*/
    DecodedDataObject destObj = null;
    try {
        srcObj = Decoder.decode(cmd.getSrcUri());
        destObj = Decoder.decode(cmd.getDestUri());
    } catch (URISyntaxException e) {
        return new Answer(cmd, false, e.toString());
    }

    if (srcObj.getPath().startsWith("http")) {
        return directDownloadHttpTemplate(cmd, srcObj, destObj);
    } else {
        return new Answer(cmd, false, "not implemented yet");
        /*
        String tmplturl = cmd.getUrl();
        String poolName = cmd.getPoolUuid();
        int wait = cmd.getWait();
        try {
        URI uri = new URI(tmplturl);
        String tmplpath = uri.getHost() + ":" + uri.getPath();
        Connection conn = hypervisorResource.getConnection();
        SR poolsr = null;
        Set<SR> srs = SR.getByNameLabel(conn, poolName);
        if (srs.size() != 1) {
        String msg = "There are " + srs.size() + " SRs with same name: " + poolName;
        s_logger.warn(msg);
        return new PrimaryStorageDownloadAnswer(msg);
        } else {
        poolsr = srs.iterator().next();
        }
        String pUuid = poolsr.getUuid(conn);
        boolean isISCSI = IsISCSI(poolsr.getType(conn));
        String uuid = copy_vhd_from_secondarystorage(conn, tmplpath, pUuid, wait);
        VDI tmpl = getVDIbyUuid(conn, uuid);
        VDI snapshotvdi = tmpl.snapshot(conn, new HashMap<String, String>());
        String snapshotUuid = snapshotvdi.getUuid(conn);
        snapshotvdi.setNameLabel(conn, "Template " + cmd.getName());
        String parentuuid = getVhdParent(conn, pUuid, snapshotUuid, isISCSI);
        VDI parent = getVDIbyUuid(conn, parentuuid);
        Long phySize = parent.getPhysicalUtilisation(conn);
        tmpl.destroy(conn);
        poolsr.scan(conn);
        try{
        Thread.sleep(5000);
        } catch (Exception e) {
        }
        return new PrimaryStorageDownloadAnswer(snapshotvdi.getUuid(conn), phySize);
        } catch (Exception e) {
        String msg = "Catch Exception " + e.getClass().getName() + " on host:" + _host.uuid + " for template: "
            + tmplturl + " due to " + e.toString();
        s_logger.warn(msg, e);
        return new PrimaryStorageDownloadAnswer(msg);
        }*/
    }

}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Method run in a separate worker thread when GetCapabilities.execute() is called.
 * Takes the server info from the ServerConnection supplied and stores it as a URI.
 * @param srvs   An array of ServerConnection objects from which to form the URI. May only contain 1.
 *///from ww  w  . j  a  v  a  2s .c om
@Override
protected GetCapabilities doInBackground(ServerConnection... srvs) {
    Log.d(TAG, "doInBackground(ServerConnection...) called.");

    mServerConnection = srvs[0]; // Stores the ServerConnection info.

    /* Try to form an URI from the supplied ServerConnection info. */
    String uriString = mServerConnection.getAddress()
            + "/wms?service=wms&version=1.1.0&request=GetCapabilities";
    try {
        mServerURI = new URI(uriString);
    } catch (URISyntaxException e) {
        Log.e(TAG, e.getMessage() + ": " + uriString);
    }

    try { // Get or wait for exclusive access to the HttpClient.
        mHttpClient = mService.getHttpClient();
    } catch (InterruptedException e) {
        Log.e(TAG, "Thread " + Thread.currentThread().getId() + ": " + e.toString());
    }

    mHasResponse = getCapabilitiesRequest(); // Make the GetCapabilities request to the server and record the success state.
    mService.unlockHttpClient(); // Release the lock on the HttpClient, allowing new connections to be made.
    Log.v(TAG, "GetCapabilities request succeeded: " + String.valueOf(mHasResponse));
    return this;
}

From source file:com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor.java

@Override
public KVMStoragePool getStoragePoolByURI(String uri) {
    URI storageUri = null;/*from  w  ww. jav a  2  s  .  co  m*/

    try {
        storageUri = new URI(uri);
    } catch (URISyntaxException e) {
        throw new CloudRuntimeException(e.toString());
    }

    String sourcePath = null;
    String uuid = null;
    String sourceHost = "";
    StoragePoolType protocal = null;
    if (storageUri.getScheme().equalsIgnoreCase("nfs")) {
        sourcePath = storageUri.getPath();
        sourcePath = sourcePath.replace("//", "/");
        sourceHost = storageUri.getHost();
        uuid = UUID.nameUUIDFromBytes(new String(sourceHost + sourcePath).getBytes()).toString();
        protocal = StoragePoolType.NetworkFilesystem;
    }

    return createStoragePool(uuid, sourceHost, 0, sourcePath, "", protocal);
}

From source file:com.grendelscan.ui.http.transactionDisplay.TransactionComposite.java

private void initGUI() {
    setLayout(new FillLayout(SWT.HORIZONTAL | SWT.VERTICAL));
    addDisposeListener(new DisposeListener() {
        @Override//from  ww w .  ja  va  2s.  c om
        public void widgetDisposed(@SuppressWarnings("unused") final DisposeEvent arg0) {
            requestParsed = requestParsedRadio.getSelection();
            if (showResponse) {
                responseParsed = responseParsedRadio.getSelection();
            }
        }
    });
    {
        tabs = new GTabFolder(this, SWT.NONE);
        {
            {
                SelectionAdapter requestFormatChange = new SelectionAdapter() {
                    @Override
                    public void widgetSelected(final SelectionEvent event) {
                        if (((GButton) event.widget).getSelection()) {
                            try {
                                updateRequestControl(true);
                            } catch (URISyntaxException e) {
                                MainWindow.getInstance().displayMessage("Error",
                                        "Illegal uri format: " + e.toString(), true);
                                event.doit = false;
                            }
                        }
                    }
                };

                httpRequestComposite = new GComposite(tabs, SWT.NONE);
                requestTab = new TabItem(tabs, SWT.NONE);
                requestTab.setText("Request");
                requestTab.setControl(httpRequestComposite);
                FormLayout httpRequestGroupLayout = new FormLayout();
                httpRequestComposite.setLayout(httpRequestGroupLayout);
                GridData httpRequestGroupLData = new GridData();
                httpRequestGroupLData.widthHint = 699;
                httpRequestGroupLData.heightHint = 283;
                httpRequestComposite.setLayoutData(httpRequestGroupLData);
                int buttonPadding = 0;
                // if (showNextButtons)
                // {
                // buttonPadding = 35;
                // {
                // previousButton = new GButton(httpRequestComposite, SWT.PUSH | SWT.CENTER);
                // FormData nextButtonLData = new FormData();
                // nextButtonLData.width = 70;
                // nextButtonLData.height = 25;
                // nextButtonLData.left = new FormAttachment(0, 1000, 5);
                // nextButtonLData.top = new FormAttachment(0, 1000, 5);
                // previousButton.setLayoutData(nextButtonLData);
                // previousButton.setText("Previous");
                // previousButton.addSelectionListener(new SelectionAdapter() {
                // @Override
                // public void widgetSelected(SelectionEvent evt) {
                // previousButtonSelected(evt);
                // }
                // });
                // }
                // {
                // nextButton = new GButton(httpRequestComposite, SWT.PUSH | SWT.CENTER);
                // FormData nextButtonLData = new FormData();
                // nextButtonLData.width = 70;
                // nextButtonLData.height = 25;
                // nextButtonLData.left = new FormAttachment(0, 1000, 80);
                // nextButtonLData.top = new FormAttachment(0, 1000, 5);
                // nextButton.setLayoutData(nextButtonLData);
                // nextButton.setText("Next");
                // nextButton.addSelectionListener(new SelectionAdapter() {
                // @Override
                // public void widgetSelected(SelectionEvent evt) {
                // nextButtonSelected(evt);
                // }
                // });
                // }
                // }
                {
                    httpRequestControlLayoutData = new FormData();
                    httpRequestControlLayoutData.left = new FormAttachment(0, 1000, 5);
                    httpRequestControlLayoutData.top = new FormAttachment(0, 1000, 15 + buttonPadding);
                    httpRequestControlLayoutData.right = new FormAttachment(1000, 1000, -5);
                    httpRequestControlLayoutData.bottom = new FormAttachment(1000, 1000, -10);
                }
                {
                    rawRequestTextBox = new GText(httpRequestComposite,
                            SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
                    rawRequestTextBox.setLayoutData(httpRequestControlLayoutData);
                    rawRequestTextBox.setEditable(requestEditable);
                    rawRequestTextBox.setVisible(!requestParsed);
                    rawRequestTextBox.addModifyListener(new ModifyListener() {
                        @Override
                        public void modifyText(final ModifyEvent arg0) {
                            rawRequestTextBox.setData(null);
                        }
                    });
                }
                {
                    parsedHttpRequest = new ParsedRequestComposite(httpRequestComposite, SWT.NONE,
                            requestEditable);
                    parsedHttpRequest.setLayoutData(httpRequestControlLayoutData);
                    parsedHttpRequest.setVisible(requestParsed);
                }
                {
                    requestParsedRadio = new GButton(httpRequestComposite, SWT.RADIO | SWT.LEFT);
                    FormData requestParsedRadioLData = new FormData();
                    requestParsedRadioLData.width = 69;
                    requestParsedRadioLData.height = 15;
                    requestParsedRadioLData.left = new FormAttachment(0, 1000, 5);
                    requestParsedRadioLData.top = new FormAttachment(0, 1000, buttonPadding);
                    requestParsedRadio.setLayoutData(requestParsedRadioLData);
                    requestParsedRadio.setText("Parsed");
                    requestParsedRadio.setSelection(requestParsed);
                    requestParsedRadio.addSelectionListener(requestFormatChange);
                }
                {
                    requestRawRadio = new GButton(httpRequestComposite, SWT.RADIO | SWT.LEFT);
                    FormData requestRawRadioLData = new FormData();
                    requestRawRadioLData.width = 49;
                    requestRawRadioLData.height = 15;
                    requestRawRadioLData.top = new FormAttachment(0, 1000, buttonPadding);
                    requestRawRadioLData.left = new FormAttachment(0, 1000, 80);
                    requestRawRadio.setLayoutData(requestRawRadioLData);
                    requestRawRadio.setText("Raw");
                    requestRawRadio.setSelection(!requestParsed);
                    requestRawRadio.addSelectionListener(requestFormatChange);
                }
            }
            if (showResponse) {
                buildResponseTab();
            }

        }

    }
    this.layout();
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Code(String destinationUrl) throws IllegalArgumentException {
    URI nakedUri;/*from ww w. ja va2  s.com*/
    try {
        nakedUri = new URI(authUrl);
    } catch (URISyntaxException e2) {
        e2.printStackTrace();
        logger.error(e2.toString());
        return getSelfUrl();
    }
    addCredentials(CLIENT_ID, CLIENT_SECRET, nakedUri.getHost());
    Context ctxt = new Context();
    stateMap.put(ctxt.getKey(), ctxt);
    ctxtKey = ctxt.getKey();

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("response_type", "code"));
    qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
    qparams.add(new BasicNameValuePair("scope", scope));
    qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
    qparams.add(new BasicNameValuePair("state", ctxt.getKey()));
    URI uri;
    try {
        uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        logger.error(e1.toString());
        return getSelfUrl();
    }

    String toString = uri.toString();
    return toString;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String getOauth2UserEmail() throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {/*from  www .  ja  v a2s.c  om*/
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    String email = null;
    {
        URI nakedUri;
        try {
            nakedUri = new URI(userInfoUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error - reason: " + response.getStatusLine().getReasonPhrase() + " status code: "
                        + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);

                    email = (String) userData.get("email");
                } else {
                    logger.error("unexpected body");
                    return "Error - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    return email;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {/*from   w  w  w.j ava 2  s.co  m*/
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - unexpected body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    {
        URI nakedUri;
        try {
            nakedUri = new URI(destinationUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error";
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.toLowerCase().contains("xml")) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                        StringBuilder b = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            b.append(line);
                        }
                        String value = b.toString();
                        return value;
                    } else {
                        logger.error("unexpected body");
                        return "Error";
                    }
                } else {
                    logger.error("unexpected missing body");
                    return "Error";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}