Example usage for org.w3c.dom Node hasChildNodes

List of usage examples for org.w3c.dom Node hasChildNodes

Introduction

In this page you can find the example usage for org.w3c.dom Node hasChildNodes.

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:com.github.podd.resources.RestletPoddClientImpl.java

private static void printNote3(NodeList nodeList) {

    for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value

            if (tempNode.getNodeName().startsWith("binding")) {

                if (tempNode.getAttributes().getNamedItem("name").getTextContent().equals("Experiment")) {

                    System.out.println("");
                    System.out.print(tempNode.getAttributes().getNamedItem("name").getTextContent() + " :  \t");
                } else {
                    System.out.print(tempNode.getAttributes().getNamedItem("name").getTextContent() + " :  \t");
                }/*from w  w w  .ja  v  a  2s  .co m*/
            } else if (tempNode.getNodeName().startsWith("literal")) {
                System.out.println(tempNode.getTextContent());
                System.out.println("");
            } else if (tempNode.getNodeName().startsWith("hasPotColumnNumberOverall")) {
                System.out.println("Lane" + ": " + tempNode.getTextContent());
            } else if (tempNode.getNodeName().startsWith("hasPotPositionTray")) {
                System.out.println("Position" + ": " + tempNode.getTextContent());
            } else {
                //System.out.println(tempNode.getNodeName() + ": " + tempNode.getTextContent());
            }

            if (tempNode.hasChildNodes()) {
                // loop again if has child node

                printNote3(tempNode.getChildNodes());
                //System.out.println("");

            }

        }

    }

}

From source file:com.piusvelte.sonet.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);//from   ww  w.jav  a 2s .c o  m
    mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE);
            mServiceName = Sonet.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID);
            mSonetWebView = new SonetWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mSonetWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mSonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL,
                        BuildConfig.FACEBOOK_ID, FACEBOOK_CALLBACK.toString()));
                break;
            case MYSPACE:
                mSonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET);
                asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE,
                        MYSPACE_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case FOURSQUARE:
                mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, BuildConfig.FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mSonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Sonet.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            case IDENTICA:
                mSonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET);
                asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case GOOGLEPLUS:
                mSonetWebView.open(String.format(GOOGLEPLUS_AUTHORIZE, BuildConfig.GOOGLECLIENT_ID,
                        "urn:ietf:wg:oauth:2.0:oob"));
                break;
            case CHATTER:
                mSonetWebView.open(String.format(CHATTER_URL_AUTHORIZE, BuildConfig.CHATTER_KEY,
                        CHATTER_CALLBACK.toString()));
                break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:org.dasein.cloud.aws.storage.S3.java

private void loadObjects(@Nonnull String regionId, @Nonnull String bucket, @Nonnull Jiterator<Blob> iterator)
        throws CloudException, InternalException {
    HashMap<String, String> parameters = new HashMap<String, String>();
    S3Response response;/*w w  w.j  a  v a2  s . co  m*/
    String marker = null;
    boolean done = false;
    S3Method method;

    while (!done) {
        NodeList blocks;

        parameters.clear();
        if (marker != null) {
            parameters.put("marker", marker);
        }
        parameters.put("max-keys", String.valueOf(30));
        method = new S3Method(provider, S3Action.LIST_CONTENTS, parameters, null);
        try {
            response = method.invoke(bucket, null);
        } catch (S3Exception e) {
            String code = e.getCode();

            if (code == null || !code.equals("SignatureDoesNotMatch")) {
                throw new CloudException(e);
            }
            logger.error(e.getSummary());
            throw new CloudException(e);
        }
        blocks = response.document.getElementsByTagName("IsTruncated");
        if (blocks.getLength() > 0) {
            done = blocks.item(0).getFirstChild().getNodeValue().trim().equalsIgnoreCase("false");
        }
        blocks = response.document.getElementsByTagName("Contents");
        for (int i = 0; i < blocks.getLength(); i++) {
            Node object = blocks.item(i);
            Storage<org.dasein.util.uom.storage.Byte> size = null;
            String name = null;
            long ts = -1L;

            if (object.hasChildNodes()) {
                NodeList attrs = object.getChildNodes();

                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);

                    if (attr.getNodeName().equalsIgnoreCase("Key")) {
                        String key = attr.getFirstChild().getNodeValue().trim();

                        name = key;
                        marker = key;
                    } else if (attr.getNodeName().equalsIgnoreCase("Size")) {
                        size = new Storage<org.dasein.util.uom.storage.Byte>(
                                Long.parseLong(attr.getFirstChild().getNodeValue().trim()), Storage.BYTE);
                    } else if (attr.getNodeName().equalsIgnoreCase("LastModified")) {
                        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                        String dateString = attr.getFirstChild().getNodeValue().trim();

                        try {
                            ts = fmt.parse(dateString).getTime();
                        } catch (ParseException e) {
                            logger.error(e);
                            e.printStackTrace();
                            throw new CloudException(e);
                        }
                    }
                }
            }
            if (name == null || size == null) {
                continue;
            }
            iterator.push(Blob.getInstance(regionId, getLocation(bucket, name), bucket, name, ts, size));
        }
    }
}

From source file:com.shafiq.myfeedle.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);//w  w  w. j  a v a 2s .c om
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:org.dasein.cloud.aws.storage.S3.java

@Override
public Blob getObject(@Nullable String bucketName, @Nonnull String objectName)
        throws InternalException, CloudException {
    APITrace.begin(provider, "Blob.getObject");
    try {//from  w  ww .  j ava 2s.  c  om
        if (bucketName == null) {
            return null;
        }
        ProviderContext ctx = provider.getContext();

        if (ctx == null) {
            throw new CloudException("No context was set for this request");
        }
        String regionId = ctx.getRegionId();

        if (regionId == null) {
            throw new CloudException("No region was set for this request");
        }
        String myRegion = getRegion(bucketName, false);

        if (!myRegion.equals(regionId)) {
            return null;
        }

        HashMap<String, String> parameters = new HashMap<String, String>();
        S3Response response;
        String marker = null;
        boolean done = false;
        S3Method method;

        while (!done) {
            NodeList blocks;

            parameters.clear();
            if (marker != null) {
                parameters.put("marker", marker);
            }
            parameters.put("max-keys", String.valueOf(30));
            method = new S3Method(provider, S3Action.LIST_CONTENTS, parameters, null);
            try {
                response = method.invoke(bucketName, null);
            } catch (S3Exception e) {
                String code = e.getCode();

                if (code == null || !code.equals("SignatureDoesNotMatch")) {
                    throw new CloudException(e);
                }
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            blocks = response.document.getElementsByTagName("IsTruncated");
            if (blocks.getLength() > 0) {
                done = blocks.item(0).getFirstChild().getNodeValue().trim().equalsIgnoreCase("false");
            }
            blocks = response.document.getElementsByTagName("Contents");
            for (int i = 0; i < blocks.getLength(); i++) {
                Node object = blocks.item(i);
                Storage<org.dasein.util.uom.storage.Byte> size = null;
                String name = null;
                long ts = -1L;

                if (object.hasChildNodes()) {
                    NodeList attrs = object.getChildNodes();

                    for (int j = 0; j < attrs.getLength(); j++) {
                        Node attr = attrs.item(j);

                        if (attr.getNodeName().equalsIgnoreCase("Key")) {
                            String key = attr.getFirstChild().getNodeValue().trim();

                            name = key;
                            marker = key;
                        } else if (attr.getNodeName().equalsIgnoreCase("Size")) {
                            size = new Storage<org.dasein.util.uom.storage.Byte>(
                                    Long.parseLong(attr.getFirstChild().getNodeValue().trim()), Storage.BYTE);
                        } else if (attr.getNodeName().equalsIgnoreCase("LastModified")) {
                            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                            String dateString = attr.getFirstChild().getNodeValue().trim();

                            try {
                                ts = fmt.parse(dateString).getTime();
                            } catch (ParseException e) {
                                logger.error(e);
                                e.printStackTrace();
                                throw new CloudException(e);
                            }
                        }
                    }
                }
                if (!objectName.equals(name) || size == null) {
                    continue;
                }
                return Blob.getInstance(regionId, getLocation(bucketName, name), bucketName, name, ts, size);
            }
        }
        return null;
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.storage.S3.java

@Override
public void makePublic(@Nullable String bucket, @Nullable String object)
        throws InternalException, CloudException {
    APITrace.begin(provider, "Blob.makePublic");
    try {/* w  w  w .  j  a v  a 2 s.  c o  m*/
        if (bucket == null) {
            throw new CloudException("No bucket was specified for this request");
        }
        Document current = getAcl(bucket, object);

        if (current == null) {
            throw new CloudException("Target does not exist");
        }
        StringBuilder xml = new StringBuilder();
        NodeList blocks;

        blocks = current.getDocumentElement().getChildNodes();
        xml.append("<AccessControlPolicy xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
        for (int i = 0; i < blocks.getLength(); i++) {
            Node n = blocks.item(i);

            if (n.getNodeName().equals("Owner")) {
                NodeList attrs = n.getChildNodes();

                xml.append("<Owner>");
                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);

                    if (attr.getNodeName().equals("ID")) {
                        xml.append("<ID>");
                        xml.append(attr.getFirstChild().getNodeValue().trim());
                        xml.append("</ID>");
                    } else if (attr.getNodeName().equals("DisplayName")) {
                        xml.append("<DisplayName>");
                        xml.append(attr.getFirstChild().getNodeValue().trim());
                        xml.append("</DisplayName>");
                    }
                }
                xml.append("</Owner>");
            } else if (n.getNodeName().equals("AccessControlList")) {
                NodeList attrs = n.getChildNodes();
                boolean found = false;

                xml.append("<AccessControlList>");
                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);

                    if (attr.getNodeName().equals("Grant")) {
                        NodeList subList = attr.getChildNodes();
                        boolean isAll = false;

                        xml.append("<Grant>");
                        for (int k = 0; k < subList.getLength(); k++) {
                            Node sub = subList.item(k);

                            if (sub.getNodeName().equals("Grantee")) {
                                String type = sub.getAttributes().getNamedItem("xsi:type").getNodeValue();
                                NodeList agentInfo = sub.getChildNodes();

                                xml.append(
                                        "<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"");
                                xml.append(type);
                                xml.append("\">");
                                for (int l = 0; l < agentInfo.getLength(); l++) {
                                    Node item = agentInfo.item(l);

                                    xml.append("<");
                                    xml.append(item.getNodeName());
                                    if (item.hasChildNodes()) {
                                        String val = item.getFirstChild().getNodeValue();

                                        if (type.equals("Group") && item.getNodeName().equals("URI") && val
                                                .equals("http://acs.amazonaws.com/groups/global/AllUsers")) {
                                            found = true;
                                            isAll = true;
                                        }
                                        xml.append(">");
                                        xml.append(item.getFirstChild().getNodeValue());
                                        xml.append("</");
                                        xml.append(item.getNodeName());
                                        xml.append(">");
                                    } else {
                                        xml.append("/>");
                                    }
                                }
                                xml.append("</Grantee>");
                            } else if (sub.getNodeName().equals("Permission")) {
                                if (isAll) {
                                    xml.append("<Permission>READ</Permission>");
                                } else {
                                    xml.append("<Permission");
                                    if (sub.hasChildNodes()) {
                                        xml.append(">");
                                        xml.append(sub.getFirstChild().getNodeValue());
                                        xml.append("</Permission>");
                                    } else {
                                        xml.append("/>");
                                    }
                                }
                            }
                        }
                        xml.append("</Grant>");
                    }
                }
                if (!found) {
                    xml.append("<Grant>");
                    xml.append(
                            "<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"Group\">");
                    xml.append("<URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>");
                    xml.append("</Grantee>");
                    xml.append("<Permission>READ</Permission>");
                    xml.append("</Grant>");
                }
                xml.append("</AccessControlList>");
            }
        }
        xml.append("</AccessControlPolicy>\r\n");
        setAcl(bucket, object, xml.toString());
    } finally {
        APITrace.end();
    }
}

From source file:com.connexta.arbitro.ConfigurationStore.java

/**
 * Private helper that is used by all the code to load an instance of the given class...this
 * assumes that the class is in the classpath, both for simplicity and for stronger security
 *///from  w w  w  . j a  va2s  . com
private Object loadClass(String prefix, Node root) throws ParsingException {
    // get the name of the class
    String className = root.getAttributes().getNamedItem("class").getNodeValue();

    if (logger.isDebugEnabled()) {
        logger.debug("Loading [ " + prefix + ": " + className + " ]");
    }

    // load the given class using the local classloader
    Class c = null;
    try {
        c = loader.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        throw new ParsingException("couldn't load class " + className, cnfe);
    }
    Object instance = null;

    // figure out if there are any parameters to the constructor
    if (!root.hasChildNodes()) {
        // we're using a null constructor, so this is easy
        try {
            instance = c.newInstance();
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className + " with empty constructor", ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        }
    } else {
        // parse the arguments to the constructor
        Set args = null;
        try {
            args = getArgs(root);
        } catch (IllegalArgumentException iae) {
            throw new ParsingException("illegal class arguments", iae);
        }
        int argLength = args.size();

        // next we need to see if there's a constructor that matches the
        // arguments provided...this has to be done by hand since
        // Class.getConstructor(Class []) doesn't handle sub-classes and
        // generic types (for instance, a constructor taking List won't
        // match a parameter list containing ArrayList)

        // get the list of all available constructors
        Constructor[] cons = c.getConstructors();
        Constructor constructor = null;

        for (int i = 0; i < cons.length; i++) {
            // get the parameters for this constructor
            Class[] params = cons[i].getParameterTypes();
            if (params.length == argLength) {
                Iterator it = args.iterator();
                int j = 0;

                // loop through the parameters and see if each one is
                // assignable from the coresponding input argument
                while (it.hasNext()) {
                    if (!params[j].isAssignableFrom(it.next().getClass()))
                        break;
                    j++;
                }

                // if we looked at all the parameters, then this
                // constructor matches the input
                if (j == argLength)
                    constructor = cons[i];
            }

            // if we've found a matching constructor then stop looping
            if (constructor != null)
                break;
        }

        // make sure we found a matching constructor
        if (constructor == null)
            throw new ParsingException("couldn't find a matching " + "constructor");

        // finally, instantiate the class
        try {
            instance = constructor.newInstance(args.toArray());
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className, ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        } catch (InvocationTargetException ite) {
            throw new ParsingException("couldn't create " + className, ite);
        }
    }

    return instance;
}

From source file:DomPrintUtil.java

/**
 * Returns XML text converted from the target DOM
 * //from  w  ww .  ja va 2  s  . c  om
 * @return String format XML converted from the target DOM
 */
public String toXMLString() {
    StringBuffer tmpSB = new StringBuffer(8192);

    TreeWalkerImpl treeWalker = new TreeWalkerImpl(document, whatToShow, nodeFilter, entityReferenceExpansion);

    String lt = escapeTagBracket ? ESC_LT : LT;
    String gt = escapeTagBracket ? ESC_GT : GT;
    String line_sep = indent ? LINE_SEP : EMPTY_STR;

    Node tmpN = treeWalker.nextNode();
    boolean prevIsText = false;

    String indentS = EMPTY_STR;
    while (tmpN != null) {
        short type = tmpN.getNodeType();
        switch (type) {
        case Node.ELEMENT_NODE:
            if (prevIsText) {
                tmpSB.append(line_sep);
            }
            tmpSB.append(indentS + lt + tmpN.getNodeName());
            NamedNodeMap attrs = tmpN.getAttributes();
            int len = attrs.getLength();
            for (int i = 0; i < len; i++) {
                Node attr = attrs.item(i);
                String value = attr.getNodeValue();
                if (null != value) {
                    tmpSB.append(getAttributeString((Element) tmpN, attr));
                }
            }
            if (tmpN instanceof HTMLTitleElement && !tmpN.hasChildNodes()) {
                tmpSB.append(gt + ((HTMLTitleElement) tmpN).getText());
                prevIsText = true;
            } else if (checkNewLine(tmpN)) {
                tmpSB.append(gt + line_sep);
                prevIsText = false;
            } else {
                tmpSB.append(gt);
                prevIsText = true;
            }
            break;
        case Node.TEXT_NODE:
            if (!prevIsText) {
                tmpSB.append(indentS);
            }
            tmpSB.append(getXMLString(tmpN.getNodeValue()));
            prevIsText = true;
            break;
        case Node.COMMENT_NODE:
            String comment;
            if (escapeTagBracket) {
                comment = getXMLString(tmpN.getNodeValue());
            } else {
                comment = tmpN.getNodeValue();
            }
            tmpSB.append(line_sep + indentS + lt + "!--" + comment + "--" + gt + line_sep);
            prevIsText = false;
            break;
        case Node.CDATA_SECTION_NODE:
            tmpSB.append(line_sep + indentS + lt + "!CDATA[" + tmpN.getNodeValue() + "]]" + line_sep);
            break;
        case Node.DOCUMENT_TYPE_NODE:
            if (tmpN instanceof DocumentType) {
                DocumentType docType = (DocumentType) tmpN;
                String pubId = docType.getPublicId();
                String sysId = docType.getSystemId();
                if (null != pubId && pubId.length() > 0) {
                    if (null != sysId && sysId.length() > 0) {
                        tmpSB.append(lt + "!DOCTYPE " + docType.getName() + " PUBLIC \"" + pubId + " \"" + sysId
                                + "\">" + line_sep);
                    } else {
                        tmpSB.append(
                                lt + "!DOCTYPE " + docType.getName() + " PUBLIC \"" + pubId + "\">" + line_sep);
                    }
                } else {
                    tmpSB.append(lt + "!DOCTYPE " + docType.getName() + " SYSTEM \"" + docType.getSystemId()
                            + "\">" + line_sep);

                }
            } else {
                System.out.println("Document Type node does not implement DocumentType: " + tmpN);
            }
            break;
        default:
            System.out.println(tmpN.getNodeType() + " : " + tmpN.getNodeName());
        }

        Node next = treeWalker.firstChild();
        if (null != next) {
            if (indent && type == Node.ELEMENT_NODE) {
                indentS = indentS + " ";
            }
            tmpN = next;
            continue;
        }

        if (tmpN.getNodeType() == Node.ELEMENT_NODE) {
            tmpSB.append(lt + "/" + tmpN.getNodeName() + gt + line_sep);
            prevIsText = false;
        }

        next = treeWalker.nextSibling();
        if (null != next) {
            tmpN = next;
            continue;
        }

        tmpN = null;
        next = treeWalker.parentNode();
        while (null != next) {
            if (next.getNodeType() == Node.ELEMENT_NODE) {
                if (indent) {
                    if (indentS.length() > 0) {
                        indentS = indentS.substring(1);
                    } else {
                        System.err.println("indent: " + next.getNodeName() + " " + next);
                    }
                }
                tmpSB.append(line_sep + indentS + lt + "/" + next.getNodeName() + gt + line_sep);
                prevIsText = false;
            }
            next = treeWalker.nextSibling();
            if (null != next) {
                tmpN = next;
                break;
            }
            next = treeWalker.parentNode();
        }
    }
    return tmpSB.toString();
}

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

private void removeBackground(Node _node) {
    // Remove any background items from the node.
    // For now we only remove the 'bgcolor' attribute.
    NamedNodeMap attributes = _node.getAttributes();
    if ((attributes != null) && (attributes.getNamedItem("bgcolor") != null))
        attributes.removeNamedItem("bgcolor");

    // If the node has children then make recursive calls to remove the
    // background items from the children too.
    if (_node.hasChildNodes()) {
        NodeList children = _node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++)
            removeBackground(children.item(i));
    }/*from  ww  w .j  a v  a 2  s .  c  o m*/
}

From source file:org.dasein.cloud.aws.platform.CloudFront.java

private Distribution toDistributionFromSummary(Node node) {
    ArrayList<String> cnames = new ArrayList<String>();
    Distribution distribution = new Distribution();
    NodeList attrs = node.getChildNodes();

    //noinspection ConstantConditions
    distribution.setProviderOwnerId(provider.getContext().getAccountNumber());
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String name;/*from w ww .j  av a 2 s .c  o  m*/

        name = attr.getNodeName();
        if (name.equals("Id")) {
            distribution.setProviderDistributionId(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equals("Status")) {
            String s = attr.getFirstChild().getNodeValue();

            distribution.setDeployed(s != null && s.trim().equalsIgnoreCase("deployed"));
        } else if (name.equals("Enabled")) {
            String s = attr.getFirstChild().getNodeValue();

            distribution.setActive(s != null && s.trim().equalsIgnoreCase("true"));
        } else if (name.equals("DomainName")) {
            distribution.setDnsName(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equals("Origin")) {
            String origin = attr.getFirstChild().getNodeValue().trim();

            distribution.setLocation(origin);
        } else if (name.equals("CNAME")) {
            cnames.add(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equals("Comment")) {
            if (attr.hasChildNodes()) {
                String comment = attr.getFirstChild().getNodeValue();

                if (comment != null) {
                    distribution.setName(comment.trim());
                }
            }
        }
    }
    if (distribution.getName() == null) {
        String name = distribution.getDnsName();

        if (name == null) {
            name = distribution.getProviderDistributionId();
            if (name == null) {
                return null;
            }
        }
        distribution.setName(name);
    }
    String[] aliases = new String[cnames.size()];
    int i = 0;
    for (String cname : cnames) {
        aliases[i++] = cname;
    }
    distribution.setAliases(aliases);
    return distribution;
}