Example usage for java.lang NumberFormatException toString

List of usage examples for java.lang NumberFormatException toString

Introduction

In this page you can find the example usage for java.lang NumberFormatException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:at.alladin.rmbt.controlServer.RegistrationResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY");

    addAllowOrigin();//from  w  w  w .  j  a v a2  s  .  co  m

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    final InetAddress clientAddress = InetAddresses.forString(clientIpRaw);
    final String clientIpString = InetAddresses.toAddrString(clientAddress);

    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw));

    final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress);
    // public_ip_asn
    final Long asn = Helperfunctions.getASN(clientAddress);
    // public_ip_as_name 
    // country_asn (2 digit country code of AS, eg. AT or EU)
    final String asName;
    final String asCountry;
    if (asn == null) {
        asName = null;
        asCountry = null;
    } else {
        asName = Helperfunctions.getASName(asn);
        asCountry = Helperfunctions.getAScountry(asn);
    }

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            int typeId = 0;

            final String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            }

            //                System.out.println(request.toString(4));

            if (conn != null) {

                final Client clientDb = new Client(conn);

                if (!request.optString("type").isEmpty()) {
                    typeId = clientDb.getTypeId(request.getString("type"));
                    if (clientDb.hasError())
                        errorList.addError(clientDb.getError());
                }

                final List<String> clientNames = Arrays
                        .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));
                final List<String> clientVersions = Arrays
                        .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*"));

                if (clientNames.contains(request.optString("client"))
                        && clientVersions.contains(request.optString("version")) && typeId > 0) {

                    UUID uuid = null;
                    final String uuidString = request.optString("uuid", "");
                    if (uuidString.length() != 0)
                        uuid = UUID.fromString(uuidString);

                    final String clientName = request.getString("client");
                    final String clientVersion = request.getString("version");

                    String timeZoneId = request.getString("timezone");
                    // String tmpTimeZoneId = timeZoneId;

                    final long clientTime = request.getLong("time");
                    final Timestamp clientTstamp = java.sql.Timestamp
                            .valueOf(new Timestamp(clientTime).toString());

                    final JSONObject location = request.optJSONObject("location");

                    long geotime = 0;
                    double geolat = 0;
                    double geolong = 0;
                    float geoaccuracy = 0;
                    double geoaltitude = 0;
                    float geobearing = 0;
                    float geospeed = 0;
                    String geoprovider = "";

                    if (!request.isNull("location")) {
                        geotime = location.optLong("time", 0);
                        geolat = location.optDouble("lat", 0);
                        geolong = location.optDouble("long", 0);
                        geoaccuracy = (float) location.optDouble("accuracy", 0);
                        geoaltitude = location.optDouble("altitude", 0);
                        geobearing = (float) location.optDouble("bearing", 0);
                        geospeed = (float) location.optDouble("speed", 0);
                        geoprovider = location.optString("provider", "");
                    }

                    Calendar timeWithZone = null;

                    if (timeZoneId.isEmpty()) {
                        timeZoneId = Helperfunctions.getTimezoneId();
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                    } else
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                    long clientUid = 0;
                    /*
                     * if (uuid == null) {
                     * clientDb.setTimeZone(timeWithZone);
                     * clientDb.setTime(tstamp);
                     * clientDb.setClient_type_id(typeId); uuid =
                     * clientDb.storeClient(); if (clientDb.hasError()) {
                     * errorList.addError(clientDb.getError()); } else {
                     * answer.put("uuid", uuid.toString()); } }
                     */

                    if (errorList.getLength() == 0 && uuid != null) {
                        clientUid = clientDb.getClientByUuid(uuid);
                        if (clientDb.hasError())
                            errorList.addError(clientDb.getError());
                    }

                    if (clientUid > 0) {

                        final String testUuid = UUID.randomUUID().toString();
                        final String testOpenUuid = UUID.randomUUID().toString();

                        boolean testServerEncryption = true; // default is
                                                             // true

                        // hack for android api <= 10 (2.3.x)
                        // using encryption with test doesn't work
                        if (request.has("plattform") && request.optString("plattform").equals("Android"))
                            if (request.has("api_level")) {
                                final String apiLevelString = request.optString("api_level");
                                try {
                                    final int apiLevel = Integer.parseInt(apiLevelString);
                                    if (apiLevel <= 10)
                                        testServerEncryption = false;
                                } catch (final NumberFormatException e) {
                                }
                            }

                        final String serverType;
                        if (request.optString("client").equals("RMBTws"))
                            serverType = "RMBTws";
                        else
                            serverType = "RMBT";

                        final Boolean ipv6;
                        if (clientAddress instanceof Inet6Address)
                            ipv6 = true;
                        else if (clientAddress instanceof Inet4Address)
                            ipv6 = false;
                        else // should never happen, unless ipv > 6 is available
                            ipv6 = null;

                        final TestServer server = getNearestServer(errorList, geolat, geolong, geotime,
                                clientIpString, asCountry, geoIpCountry, serverType, testServerEncryption,
                                ipv6);

                        try {
                            if (server == null)
                                throw new JSONException("could not find server");

                            if (timeZoneId.isEmpty()) {
                                timeZoneId = Helperfunctions.getTimezoneId();
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                            } else
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                            answer.put("test_server_address", server.address);
                            answer.put("test_server_port", server.port);
                            answer.put("test_server_name", server.name);
                            answer.put("test_server_encryption", testServerEncryption);

                            answer.put("test_duration", getSetting("rmbt_duration"));
                            answer.put("test_numthreads", getSetting("rmbt_num_threads"));
                            answer.put("test_numpings", getSetting("rmbt_num_pings"));

                            answer.put("client_remote_ip", clientIpString);

                            final String resultUrl = new Reference(getURL(),
                                    settings.getString("RMBT_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_url", resultUrl);

                            final String resultQoSUrl = new Reference(getURL(),
                                    settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_qos_url", resultQoSUrl);
                        } catch (final JSONException e) {
                            System.out.println("Error generating Answer " + e.toString());
                            errorList.addError("ERROR_RESPONSE_JSON");

                        }

                        if (errorList.getLength() == 0)
                            try {

                                PreparedStatement st;
                                st = conn.prepareStatement(
                                        "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)"
                                                + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                                        Statement.RETURN_GENERATED_KEYS);

                                int i = 1;
                                // uuid
                                st.setObject(i++, UUID.fromString(testUuid));
                                // open_test_uuid
                                st.setObject(i++, UUID.fromString(testOpenUuid));
                                // client_id
                                st.setLong(i++, clientUid);
                                // client_name
                                st.setString(i++, clientName);
                                // client_version
                                st.setString(i++, clientVersion);
                                // client_software_version
                                st.setString(i++, request.optString("softwareVersion", null));
                                // client_language
                                st.setString(i++, lang);
                                // client_public_ip
                                st.setString(i++, clientIpString);
                                // client_public_ip_anonymized
                                st.setString(i++, Helperfunctions.anonymizeIp(clientAddress));
                                // country_geoip (2digit country code derived from public IP of client)
                                st.setString(i++, geoIpCountry);
                                // server_id
                                st.setInt(i++, server.id);
                                // port
                                st.setInt(i++, server.port);
                                // use_ssl
                                st.setBoolean(i++, testServerEncryption);
                                // timezone (of client)
                                st.setString(i++, timeZoneId);
                                // client_time (local time of client)
                                st.setTimestamp(i++, clientTstamp, timeWithZone);
                                // duration (requested)
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_duration")));
                                // num_threads_requested 
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_num_threads")));
                                // status (of test)
                                st.setString(i++, "STARTED"); //was "RUNNING" before
                                // software_revision (of client)
                                st.setString(i++, request.optString("softwareRevision", null));
                                // client_test_counter (number of tests the client has performed)
                                final int testCounter = request.optInt("testCounter", -1);
                                if (testCounter == -1) // older clients did not support testCounter
                                    st.setNull(i++, Types.INTEGER);
                                else
                                    st.setLong(i++, testCounter);
                                // client_previous_test_status (outcome of previous test)
                                st.setString(i++, request.optString("previousTestStatus", null));
                                // AS name
                                if (asn == null)
                                    st.setNull(i++, Types.BIGINT);
                                else
                                    st.setLong(i++, asn);
                                if (asName == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asName);
                                // AS country
                                if (asCountry == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asCountry);
                                //public_ip_rdns
                                String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress);
                                if (reverseDNS == null || reverseDNS.isEmpty())
                                    st.setNull(i++, Types.VARCHAR);
                                else {
                                    reverseDNS = reverseDNS.replaceFirst("\\.$", "");
                                    st.setString(i++, reverseDNS); // cut off last dot (#332)
                                }
                                // run_ndt
                                if (request.has("ndt"))
                                    st.setBoolean(i++, request.getBoolean("ndt"));
                                else
                                    st.setNull(i++, Types.BOOLEAN);

                                final int affectedRows = st.executeUpdate();
                                if (affectedRows == 0)
                                    errorList.addError("ERROR_DB_STORE_TEST");
                                else {
                                    long key = 0;
                                    final ResultSet rs = st.getGeneratedKeys();
                                    if (rs.next())
                                        // Retrieve the auto generated
                                        // key(s).
                                        key = rs.getLong(1);
                                    rs.close();

                                    final PreparedStatement getProviderSt = conn
                                            .prepareStatement("SELECT rmbt_set_provider_from_as(?)");
                                    getProviderSt.setLong(1, key);
                                    String provider = null;
                                    if (getProviderSt.execute()) {
                                        final ResultSet rs2 = getProviderSt.getResultSet();
                                        if (rs2.next())
                                            provider = rs2.getString(1);
                                    }

                                    if (provider != null)
                                        answer.put("provider", provider);

                                    final PreparedStatement testSlotStatement = conn
                                            .prepareStatement("SELECT rmbt_get_next_test_slot(?)");
                                    testSlotStatement.setLong(1, key);
                                    int testSlot = -1;
                                    if (testSlotStatement.execute()) {
                                        final ResultSet rs2 = testSlotStatement.getResultSet();
                                        if (rs2.next())
                                            testSlot = rs2.getInt(1);
                                    }

                                    if (testSlot < 0)
                                        errorList.addError("ERROR_DB_STORE_GENERAL");
                                    else {
                                        final String data = testUuid + "_" + testSlot;
                                        final String hmac = Helperfunctions.calculateHMAC(secret, data);
                                        if (hmac.length() == 0)
                                            errorList.addError("ERROR_TEST_TOKEN");
                                        final String token = data + "_" + hmac;

                                        final PreparedStatement updateSt = conn
                                                .prepareStatement("UPDATE test SET token = ? WHERE uid = ?");
                                        updateSt.setString(1, token);
                                        updateSt.setLong(2, key);
                                        updateSt.executeUpdate();

                                        answer.put("test_token", token);

                                        answer.put("test_uuid", testUuid);
                                        answer.put("test_id", key);

                                        final long now = System.currentTimeMillis();
                                        int wait = testSlot - (int) (now / 1000);
                                        if (wait < 0)
                                            wait = 0;

                                        answer.put("test_wait", wait);

                                        if (geotime != 0 && geolat != 0 && geolong != 0) {

                                            final GeoLocation clientLocation = new GeoLocation(conn);

                                            clientLocation.setTest_id(key);

                                            final Timestamp geotstamp = java.sql.Timestamp
                                                    .valueOf(new Timestamp(geotime).toString());
                                            clientLocation.setTime(geotstamp, timeZoneId);

                                            clientLocation.setAccuracy(geoaccuracy);
                                            clientLocation.setAltitude(geoaltitude);
                                            clientLocation.setBearing(geobearing);
                                            clientLocation.setSpeed(geospeed);
                                            clientLocation.setProvider(geoprovider);
                                            clientLocation.setGeo_lat(geolat);
                                            clientLocation.setGeo_long(geolong);

                                            clientLocation.storeLocation();

                                            if (clientLocation.hasError())
                                                errorList.addError(clientLocation.getError());
                                        }
                                    }
                                }

                                st.close();
                            } catch (final SQLException e) {
                                errorList.addError("ERROR_DB_STORE_GENERAL");
                                e.printStackTrace();

                            }

                    } else
                        errorList.addError("ERROR_CLIENT_UUID");

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");
            //                System.out.println(answer.toString(4));
        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:com.microhealthllc.mbmicalc.BmiChartBloodRed.java

public void bmifunc(double height, double weight) {

    try {/* w  w  w  .ja v  a2  s .c  om*/

    } catch (NumberFormatException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.error_enter_valid)).setPositiveButton(getString(R.string.ok_bro),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        // Create the AlertDialog object and return it
        builder.create();
        builder.show();
        return;
    }

    try {
        bmi = calcBMI(height, weight, this, metrics);
        //  Log.i("BMI data", ""+bmi);
        // Log.i("BMI data metric", ""+metrics);
    } catch (IllegalArgumentException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(e.getMessage()).setPositiveButton(getString(R.string.ok_bro),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        builder.create();
        builder.show();
        return;
    }
    ;
    //  bmitext.setText( df.format(bmi).toString());
    bar1.setcolors(Color.YELLOW, Color.YELLOW, Color.YELLOW);
    bar1.setcolor3(Color.YELLOW);
    bar1.setcolor1(Color.YELLOW);
    bar1.setcolor2(Color.YELLOW);
    bar1.setCurrentValues(bmi);

    // Log.i("getweight gotheight",   gotheight+","+gotWeight);

    bmi_note.setText(getString(BMIUtils.getJudgement(bmi)));
    displayheight.setText(String.format("%.0f", height));
    displayweight.setText(String.format("%.0f", weight));
    displaybmi.setText(String.format("%.1f", bmi));
    editor = sharedPref.edit();
    editor.putString(getString(R.string.display_height), String.format("%.0f", height));
    editor.putString(getString(R.string.display_weight), String.format("%.0f", weight));
    editor.putString(getString(R.string.display_note), getString(BMIUtils.getJudgement(bmi)));
    editor.putString(getString(R.string.display_bmi), String.format("%.1f", bmi));

    editor.apply();

    try {
        // if(getDateTime().equals())
        if (db.getLast().getDateTime() == null) {

            db.addLog(new BmiLogs(String.format("%.1f", bmi), String.format("%.0f", weight), getDateTime()));
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();
        } else if (db.getLast().getDateTime().equals(getDateTime())) {
            Log.i("Equals", "" + db.getLast().getDateTime().equals(getDateTime()));
            db.updateLastEntry(db.getLast().getId(), String.format("%.1f", bmi), String.format("%.0f", weight),
                    getDateTime());
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();

        } else {
            db.addLog(new BmiLogs(String.format("%.1f", bmi), String.format("%.0f", weight), getDateTime()));
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();
        }
        //  Log.i("datetime",) ;

    } catch (Exception e) {
        Log.d("Error  Exception", e.toString());
    }
}

From source file:com.microhealthllc.mbmicalc.BmiChart.java

public void bmifunc(double height, double weight) {

    try {/*  www  . ja v a  2  s.co m*/

    } catch (NumberFormatException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.error_enter_valid)).setPositiveButton(getString(R.string.ok_bro),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        // Create the AlertDialog object and return it
        builder.create();
        builder.show();
        return;
    }

    try {
        bmi = calcBMI(height, weight, this, metrics);
        //  Log.i("BMI data", ""+bmi);
        // Log.i("BMI data metric", ""+metrics);
    } catch (IllegalArgumentException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(e.getMessage()).setPositiveButton(getString(R.string.ok_bro),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        builder.create();
        builder.show();
        return;
    }
    ;
    //  bmitext.setText( df.format(bmi).toString());
    bar1.setcolors(Color.YELLOW, Color.YELLOW, Color.YELLOW);
    bar1.setcolor3(Color.YELLOW);
    bar1.setcolor1(Color.YELLOW);
    bar1.setcolor2(Color.YELLOW);

    bar1.setCurrentValues(bmi);

    // Log.i("getweight gotheight",   gotheight+","+gotWeight);

    bmi_note.setText(getString(BMIUtils.getJudgement(bmi)));
    displayheight.setText(String.format("%.0f", height));
    displayweight.setText(String.format("%.0f", weight));
    displaybmi.setText(String.format("%.1f", bmi));
    editor = sharedPref.edit();
    editor.putString(getString(R.string.display_height), String.format("%.0f", height));
    editor.putString(getString(R.string.display_weight), String.format("%.0f", weight));
    editor.putString(getString(R.string.display_note), getString(BMIUtils.getJudgement(bmi)));
    editor.putString(getString(R.string.display_bmi), String.format("%.1f", bmi));

    editor.apply();

    try {
        // if(getDateTime().equals())
        if (db.getLast().getDateTime() == null) {

            db.addLog(new BmiLogs(String.format("%.1f", bmi), String.format("%.0f", weight), getDateTime()));
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();
        } else if (db.getLast().getDateTime().equals(getDateTime())) {
            Log.i("Equals", "" + db.getLast().getDateTime().equals(getDateTime()));
            db.updateLastEntry(db.getLast().getId(), String.format("%.1f", bmi), String.format("%.0f", weight),
                    getDateTime());
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();

        } else {
            db.addLog(new BmiLogs(String.format("%.1f", bmi), String.format("%.0f", weight), getDateTime()));
            lastactivty.setText("" + getDateTimeforLastActivity());
            editor.putString(getString(R.string.last_activity), getDateTimeforLastActivity());
            editor.apply();
        }
        //  Log.i("datetime",) ;

    } catch (Exception e) {
        Log.d("Error  Exception", e.toString());
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService.java

@Override
public ObjectList getContentChanges(String repositoryId, Holder<String> changeLogTokenHolder,
        Boolean includeProperties, String filter, Boolean includePolicyIds, Boolean includeAcl,
        BigInteger maxItems, ExtensionsData extension) {
    if (changeLogTokenHolder == null) {
        throw new CmisInvalidArgumentException("Missing change log token holder");
    }/*from  w w w . ja v a 2  s  . c o  m*/
    String changeLogToken = changeLogTokenHolder.getValue();
    long minDate;
    if (changeLogToken == null) {
        minDate = 0;
    } else {
        try {
            minDate = Long.parseLong(changeLogToken);
        } catch (NumberFormatException e) {
            throw new CmisInvalidArgumentException("Invalid change log token");
        }
    }
    try {
        AuditReader reader = Framework.getService(AuditReader.class);
        if (reader == null) {
            throw new CmisRuntimeException("Cannot find audit service");
        }
        int max = maxItems == null ? -1 : maxItems.intValue();
        if (max <= 0) {
            max = DEFAULT_CHANGE_LOG_SIZE;
        }
        if (max > MAX_CHANGE_LOG_SIZE) {
            max = MAX_CHANGE_LOG_SIZE;
        }
        List<ObjectData> ods = null;
        // retry with increasingly larger page size if some items are
        // skipped
        for (int scale = 1; scale < 128; scale *= 2) {
            int pageSize = max * scale + 1;
            if (pageSize < 0) { // overflow
                pageSize = Integer.MAX_VALUE;
            }
            ods = readAuditLog(repositoryId, minDate, max, pageSize);
            if (ods != null) {
                break;
            }
            if (pageSize == Integer.MAX_VALUE) {
                break;
            }
        }
        if (ods == null) {
            // couldn't find enough, too many items were skipped
            ods = Collections.emptyList();

        }
        boolean hasMoreItems = ods.size() > max;
        if (hasMoreItems) {
            ods = ods.subList(0, max);
        }
        String latestChangeLogToken;
        if (ods.size() == 0) {
            latestChangeLogToken = null;
        } else {
            ObjectData last = ods.get(ods.size() - 1);
            latestChangeLogToken = String.valueOf(last.getChangeEventInfo().getChangeTime().getTimeInMillis());
        }
        ObjectListImpl ol = new ObjectListImpl();
        ol.setHasMoreItems(Boolean.valueOf(hasMoreItems));
        ol.setObjects(ods);
        ol.setNumItems(BigInteger.valueOf(-1));
        changeLogTokenHolder.setValue(latestChangeLogToken);
        return ol;
    } catch (Exception e) {
        throw new CmisRuntimeException(e.toString(), e);
    }
}

From source file:com.funambol.email.content.ContentProviderServlet.java

/**
 *
 * @param request/*from   w  ww.j a v a  2  s .  c  o  m*/
 * @param response
 * @throws java.io.IOException
 */
private void replyAttachment(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ContentProviderManager contentServiceManager = new ContentProviderManager();

    HttpSession session = request.getSession();

    try {
        if (log.isTraceEnabled()) {
            log.trace("Start Handling request.");
        }

        String authToken = request.getParameter(PARAMETER_AUTH);
        if (authToken == null || "".equals(authToken)) {
            printErrorPage(request, response, "The authorization parameter is empty", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Authorization token: " + authToken);
        }

        String username = request.getParameter(PARAMETER_USER);
        if (username == null || "".equals(username)) {
            printErrorPage(request, response, "The user name parameter is empty", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("User name: " + username);
        }

        String attachIdx = request.getParameter(PARAMETER_INDEX);
        if (attachIdx == null || "".equals(attachIdx)) {
            printErrorPage(request, response, "The attachment index parameter is empty", null);
            return;
        }
        int attachmentIndex = 0;
        try {
            attachmentIndex = Integer.parseInt(attachIdx);
        } catch (NumberFormatException ex) {
            printErrorPage(request, response, "Parameter \"attachment index\" must be a valid number", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Attachment index: " + attachmentIndex);
        }

        MailServerAccount mailServerAccount = contentServiceManager.retrieveMailServerAccount(username);
        if (mailServerAccount == null) {
            printErrorPage(request, response, "No valid mail server account found for user '" + username + "'",
                    null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Retrieved MailServerAccount for user '" + username + "'");
        }

        String mailServerProtocol = mailServerAccount.getMailServer().getProtocol();
        if (mailServerProtocol == null || "".equals(mailServerProtocol)) {
            printErrorPage(request, response, "The mail server account protocol is not defined", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Mail server protocol: " + mailServerProtocol);
        }

        contentServiceManager.openConnection(mailServerAccount);

        String mailGUID = contentServiceManager.authorize(username, authToken);
        if (mailGUID == null || "".equals(mailGUID)) {
            printErrorPage(request, response, "Email retrieving is not authorized"
                    + " or the email is not present in the Inbox folder anymore.", null);
            return;
        }
        String messageid = Utility.getKeyPart(mailGUID, 2);
        if (messageid == null || "".equals(messageid)) {
            printErrorPage(request, response, "Unable to retrieve the message id ", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Message ID: " + messageid);
        }

        Message message = contentServiceManager.getMessage(messageid);
        if (message == null) {
            printErrorPage(request, response,
                    "The email is not present in " + "the Inbox folder anymore (id " + messageid + ").", null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Retrieved mail from mail server with Message ID: " + messageid);
        }

        List partsList = MessageParser.getAllPartsOfMessage(message, false);
        if (partsList == null) {
            printErrorPage(request, response, "The email doesn't have attachments", null);
            return;
        }

        InternalPart part = getInternalPart(partsList, attachmentIndex);
        if (part == null) {
            printErrorPage(request, response,
                    "The email doesn't have attachments" + " with index " + attachmentIndex, null);
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Retrieved part with index: " + attachmentIndex);
        }

        if (part == null || part.getDHandler() == null || part.getDHandler().getInputStream() == null) {
            printErrorPage(request, response, "Error while streaming the attachment.", null);
            return;
        }
        InputStream in = part.getDHandler().getInputStream();

        response.setContentType(ContentProviderUtil.createHttpContentType(part));
        response.setHeader("Content-Disposition", " filename=\"" + part.getFileName() + "\"");
        OutputStream out = response.getOutputStream();

        IOUtils.copy(in, out);
        out.flush();
        out.close();
        in.close();

    } catch (Exception ex) {
        printErrorPage(request, response, ex.toString(), ex);

    } finally {
        try {
            contentServiceManager.closeConnection();
            if (log.isTraceEnabled()) {
                log.trace("Connection closed");
            }
        } catch (ContentProviderException ex) {
            log.error("Error closing connection ", ex);
        }
        if (log.isTraceEnabled()) {
            log.trace("End handling request.");
        }
        //
        // Since the session is not really useful, we force that a request is
        // served by a new session and that a session serves just one request.
        // In such way, we don't have useless sessions. As drawback for every
        // request a new session is created. 
        // Comparing advantages vs drawbacks, we prefer one session - one request.
        //
        session.invalidate();
    }
}

From source file:org.jab.docsearch.DocSearch.java

private void doHandlers() {
    DsProperties hd = new DsProperties(this, I18n.getString("windowtitle.settings"), true);
    hd.init();//from   ww  w  . j  a  v  a2  s . c  om
    hd.setVisible(true);

    if (hd.getConfirmed()) {
        // check everything
        switch (hd.getReturnInt()) {
        default: // nothing
            break;
        case 0: // default hdnler
            defaultHndlr = hd.defltHndlrText();
            break;
        case 1: // look and feel
            String newLafChosen = hd.lafSelected();
            // set new LAF if a new one is set
            if ((!newLafChosen.equals("")) && (!newLafChosen.equals(lafChosen))) {
                lafChosen = newLafChosen;
                try {
                    UIManager.setLookAndFeel(lafChosen);
                    SwingUtilities.updateComponentTreeUI(this);
                    setSize(new Dimension(kDefaultX, kDefaultY));
                } catch (Exception e) {
                    logger.error("doHandler() failed", e);
                    showMessage(I18n.getString("error"), e.toString());
                }
            }

            // now for max file size to index
            try {
                long newMFSI = Long.parseLong(hd.maxSizeField());
                if (newMFSI > 0) {
                    newMFSI = newMFSI * 1024;
                }
                setMaxFileSize(newMFSI);
            } catch (NumberFormatException nfe) {
                logger.error("doHandler() failed ", nfe);
                showMessage(I18n.getString("error"), nfe.toString());
            }

            // now for max hits to show
            String newMaxInt = hd.maxFieldText().trim();
            if (!newMaxInt.equals("")) {
                try {
                    int newMaxN = Integer.parseInt(newMaxInt);
                    if ((newMaxN > 0) && (newMaxN < 1000)) {
                        maxNumHitsShown = newMaxN;
                    }
                } catch (NumberFormatException nfe) {
                    logger.error("doHandler() failed", nfe);
                    showMessage(I18n.getString("error"), nfe.toString());
                }
            }

            if (hd.loadExternalSelected()) {
                loadExternal = true;
            } else {
                loadExternal = false;
            }
            break;
        case 2: // index directory
            //
            String newIndexDir = hd.getDsDirFieldText().trim();
            if (!newIndexDir.equals("")) {
                // copy over our files
                if (hd.copyDirFilesSelected()) {
                    // including our index list file
                    copyFiles(fEnv.getIndexDirectory(), newIndexDir);
                    // change the file settings on the DsIndex objects
                    Iterator<DocSearcherIndex> iterator = indexes.iterator();
                    DocSearcherIndex curI;
                    String curIdxrStr = "";
                    while (iterator.hasNext()) {
                        curI = iterator.next();
                        curIdxrStr = curI.getIndexPath();
                        if (curIdxrStr.startsWith(fEnv.getIndexDirectory())) {
                            curI.setIndexPath(newIndexDir + curIdxrStr
                                    .substring(fEnv.getIndexDirectory().length(), curIdxrStr.length()));
                        }
                    }
                    setStatus(I18n.getString("finished_copying"));
                }
                fEnv.setIndexDirectory(newIndexDir);
            }
            String newDirFieldTExt = hd.getTmpFieldText().trim();
            //
            if (!newDirFieldTExt.equals("")) {
                resetTempDir(newDirFieldTExt);
            }
            //
            String newWorkingDirFieldTExt = hd.workingDirFieldText().trim();
            if (!newWorkingDirFieldTExt.equals("")) {
                resetWorkingDir(newWorkingDirFieldTExt);
            }
            break;
        case 3: // email stuff
            gateway = hd.getGateWayFieldText();
            gatewayPwd = hd.gatewayPwdFieldText();
            gatewayUser = hd.gatewayUserFieldText();
            if (hd.sendEmailBxSelected()) {
                sendEmailNotice = "true";
            } else {
                sendEmailNotice = "false";
            }
            if (hd.textRBSelected()) {
                emailFormat = hd.TEXT_FORMAT;
            } else {
                emailFormat = hd.HTML_FORMAT;
            }
            break;
        }
    }
}

From source file:org.eclipse.ecr.opencmis.impl.server.NuxeoCmisService.java

@Override
public ObjectList getContentChanges(String repositoryId, Holder<String> changeLogTokenHolder,
        Boolean includeProperties, String filter, Boolean includePolicyIds, Boolean includeAcl,
        BigInteger maxItems, ExtensionsData extension) {
    if (changeLogTokenHolder == null) {
        throw new CmisInvalidArgumentException("Missing change log token holder");

    }/* www .jav a  2s . com*/
    String changeLogToken = changeLogTokenHolder.getValue();
    long minDate;
    if (changeLogToken == null) {
        minDate = 0;
    } else {
        try {
            minDate = Long.parseLong(changeLogToken);
        } catch (NumberFormatException e) {
            throw new CmisInvalidArgumentException("Invalid change log token");
        }
    }
    try {
        AuditReader reader = Framework.getService(AuditReader.class);
        if (reader == null) {
            throw new CmisRuntimeException("Cannot find audit service");
        }
        int max = maxItems == null ? -1 : maxItems.intValue();
        if (max < 0) {
            max = DEFAULT_CHANGE_LOG_SIZE;
        }
        // TODO XXX repositoryId as well
        Map<String, Object> params = new HashMap<String, Object>();
        String query = "FROM LogEntry log" //
                + " WHERE log.eventDate >= :minDate" //
                + "   AND log.eventId IN (:evCreated, :evModified, :evRemoved)" //
                + " ORDER BY log.eventDate";
        params.put("minDate", new Date(minDate));
        params.put("evCreated", DocumentEventTypes.DOCUMENT_CREATED);
        params.put("evModified", DocumentEventTypes.DOCUMENT_UPDATED);
        params.put("evRemoved", DocumentEventTypes.DOCUMENT_REMOVED);
        List<?> entries = reader.nativeQuery(query, params, 1, max + 1);
        ObjectListImpl ol = new ObjectListImpl();
        boolean hasMoreItems = entries.size() > max;
        ol.setHasMoreItems(Boolean.valueOf(hasMoreItems));
        if (hasMoreItems) {
            entries = entries.subList(0, max);
        }
        List<ObjectData> ods = new ArrayList<ObjectData>(entries.size());
        Date date = null;
        for (Object entry : entries) {
            LogEntry logEntry = (LogEntry) entry;
            ObjectDataImpl od = new ObjectDataImpl();
            ChangeEventInfoDataImpl cei = new ChangeEventInfoDataImpl();
            // change type
            String eventId = logEntry.getEventId();
            ChangeType changeType;
            if (DocumentEventTypes.DOCUMENT_CREATED.equals(eventId)) {
                changeType = ChangeType.CREATED;
            } else if (DocumentEventTypes.DOCUMENT_UPDATED.equals(eventId)) {
                changeType = ChangeType.UPDATED;
            } else if (DocumentEventTypes.DOCUMENT_REMOVED.equals(eventId)) {
                changeType = ChangeType.DELETED;
            } else {
                continue;
            }
            cei.setChangeType(changeType);
            // change time
            GregorianCalendar changeTime = (GregorianCalendar) Calendar.getInstance();
            date = logEntry.getEventDate();
            changeTime.setTime(date);
            cei.setChangeTime(changeTime);
            od.setChangeEventInfo(cei);
            // properties: id, doc type
            PropertiesImpl properties = new PropertiesImpl();
            properties.addProperty(new PropertyIdImpl(PropertyIds.OBJECT_ID, logEntry.getDocUUID()));
            properties.addProperty(new PropertyIdImpl(PropertyIds.OBJECT_TYPE_ID, logEntry.getDocType()));
            od.setProperties(properties);
            ods.add(od);
        }
        ol.setObjects(ods);
        ol.setNumItems(BigInteger.valueOf(-1));
        String latestChangeLogToken = date == null ? null : String.valueOf(date.getTime());
        changeLogTokenHolder.setValue(latestChangeLogToken);
        return ol;
    } catch (Exception e) {
        throw new CmisRuntimeException(e.toString(), e);
    }
}

From source file:org.hippoecm.hst.demo.components.NonWorkflowWikiImporterComponent.java

@Override
public void doAction(HstRequest request, HstResponse response) throws HstComponentException {
    String numberStr = request.getParameter("number");
    long start = System.currentTimeMillis();
    if (numberStr != null) {
        SAXParserFactoryImpl impl = new SAXParserFactoryImpl();
        SAXParser parser;/*from ww  w .  j ava 2s  . c  om*/
        int numberOfWikiDocs = 0;
        try {
            numberOfWikiDocs = Integer.parseInt(numberStr);
        } catch (NumberFormatException e) {
            response.setRenderParameter("message", "number must be a number but was '" + numberStr + "'");
        }

        if (numberOfWikiDocs <= 0) {
            response.setRenderParameter("message",
                    "number must be a number larger than 0 but was '" + numberStr + "'");
        }

        String wikiContentFileSystem = request.getParameter("filesystemLocation");

        if (numberOfWikiDocs > 100 && StringUtils.isEmpty(wikiContentFileSystem)) {
            response.setRenderParameter("message",
                    "When number is larger than 100, you need to specify the filesystem location (for exmaple /home/use/Downloads/enwiki-20100622-pages-articles.xml) where wikipedia content can be found that "
                            + "has more than 100 docs. If you choose less than 100, a built in wikipedia xml is used that contains 100 items");
            return;
        }

        String offsetStr = request.getParameter("offset");
        int offset = 0;
        if (StringUtils.isNotBlank(offsetStr)) {
            try {
                offset = Integer.parseInt(offsetStr);
                if (offset < 0) {
                    offset = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message", "offset must be a number but was '" + offsetStr + "'");
                return;
            }
        }

        String maxDocsPerFolderStr = request.getParameter("maxDocsPerFolder");
        int maxDocsPerFolder = 200;
        if (StringUtils.isNotBlank(maxDocsPerFolderStr)) {
            try {
                maxDocsPerFolder = Integer.parseInt(maxDocsPerFolderStr);
                if (maxDocsPerFolder < 0) {
                    maxDocsPerFolder = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "maxDocsPerFolder must be a number but was '" + maxDocsPerFolderStr + "'");
                return;
            }
        }

        String maxSubFolderStr = request.getParameter("maxSubFolder");
        int maxSubFolder = 50;
        if (StringUtils.isNotBlank(maxSubFolderStr)) {
            try {
                maxSubFolder = Integer.parseInt(maxSubFolderStr);
                if (maxSubFolder < 0) {
                    maxSubFolder = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "maxSubFolder must be a number but was '" + maxSubFolderStr + "'");
                return;
            }
        }

        String imageStr = request.getParameter("images");
        boolean addImages = (imageStr != null);

        try {
            parser = impl.newSAXParser();
            InputStream wikiStream = null;
            File f = null;
            if (StringUtils.isEmpty(wikiContentFileSystem)) {
                wikiStream = NonWorkflowWikiImporterComponent.class.getClassLoader()
                        .getResourceAsStream("enwiki-20081008-pages-articles.xml.100.top.xml");
            } else {
                f = new File(wikiContentFileSystem);
            }

            WikiPediaToJCRHandler handler = null;

            try {
                Session writableSession = this.getPersistableSession(request);
                Node baseNode = writableSession.getNode("/" + getSiteContentBasePath(request));

                Node wikiFolder;

                if (!baseNode.hasNode("wikipedia")) {
                    wikiFolder = baseNode.addNode("wikipedia", "hippostd:folder");
                    wikiFolder.setProperty("hippostd:foldertype",
                            new String[] { "new-translated-folder-demosite", "new-document-demosite" });
                    wikiFolder.addMixin("mix:referenceable");
                    wikiFolder.addMixin("hippotranslation:translated");
                    wikiFolder.setProperty("hippotranslation:locale", "en");
                    wikiFolder.setProperty("hippotranslation:id", UUID.randomUUID().toString());
                } else {
                    wikiFolder = baseNode.getNode("wikipedia");
                }

                handler = new WikiPediaToJCRHandler(wikiFolder, numberOfWikiDocs, offset, maxDocsPerFolder,
                        maxSubFolder, addImages);

                if (wikiStream == null) {
                    parser.parse(f, handler);
                } else {
                    parser.parse(wikiStream, handler);
                }
            } catch (ForcedStopException e) {
                // successful handler quits after numberOfWikiDocs has been achieved
            } catch (Exception e) {
                log.warn("Exception during importing wikipedia docs", e);
                response.setRenderParameter("message",
                        "An exception happened. Did not import wiki docs. " + e.toString());
                return;
            }
        } catch (ParserConfigurationException e) {
            response.setRenderParameter("message", "Did not import wiki: " + e.toString());
            return;
        }
        String relateString = request.getParameter("relate");
        if (relateString != null) {
            int numberOfRelations = 0;
            try {
                numberOfRelations = Integer.parseInt(relateString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of relations must be a number but was '" + relateString + "'");
            }
            relateDocuments(request, response, getRelateNodesOperation(), numberOfRelations, "uuid");
        }

        String linkString = request.getParameter("link");
        if (linkString != null) {
            int numberOfLinks = 0;
            try {
                numberOfLinks = Integer.parseInt(linkString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of links must be a number but was '" + linkString + "'");
            }
            relateDocuments(request, response, getLinkNodesOperation(), numberOfLinks, "versionHistory");
        }

        String translateString = request.getParameter("translate");
        if (translateString != null) {
            int numberOfTranslations = 0;
            try {
                numberOfTranslations = Integer.parseInt(translateString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of translations must be a number but was '" + translateString + "'");
            }
            relateDocuments(request, response, getTranslateOperation(), numberOfTranslations, "uuid");
        }
    }

    response.setRenderParameter("message",
            "Successfully completed operation in " + (System.currentTimeMillis() - start) + "ms.");
}

From source file:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

public String getLowestAvailableVIFDeviceNum(final Connection conn, final VM vm) {
    String vmName = "";
    try {//from  w w  w .  j a va  2s.c  o  m
        vmName = vm.getNameLabel(conn);
        final List<Integer> usedDeviceNums = new ArrayList<Integer>();
        final Set<VIF> vifs = vm.getVIFs(conn);
        final Iterator<VIF> vifIter = vifs.iterator();
        while (vifIter.hasNext()) {
            final VIF vif = vifIter.next();
            try {
                final String deviceId = vif.getDevice(conn);
                if (vm.getIsControlDomain(conn) || vif.getCurrentlyAttached(conn)) {
                    usedDeviceNums.add(Integer.valueOf(deviceId));
                } else {
                    s_logger.debug("Found unplugged VIF " + deviceId + " in VM " + vmName + " destroy it");
                    vif.destroy(conn);
                }
            } catch (final NumberFormatException e) {
                final String msg = "Obtained an invalid value for an allocated VIF device number for VM: "
                        + vmName;
                s_logger.debug(msg, e);
                throw new CloudRuntimeException(msg);
            }
        }

        for (Integer i = 0; i < _maxNics; i++) {
            if (!usedDeviceNums.contains(i)) {
                s_logger.debug("Lowest available Vif device number: " + i + " for VM: " + vmName);
                return i.toString();
            }
        }
    } catch (final XmlRpcException e) {
        final String msg = "Caught XmlRpcException: " + e.getMessage();
        s_logger.warn(msg, e);
    } catch (final XenAPIException e) {
        final String msg = "Caught XenAPIException: " + e.toString();
        s_logger.warn(msg, e);
    }

    throw new CloudRuntimeException("Could not find available VIF slot in VM with name: " + vmName);
}

From source file:org.sakaiproject.content.chh.dspace.ContentHostingHandlerImplDSpace.java

private DSpaceItemInfo queryDSpaceFor(String endpoint, String base, String needle) {
    try {//from  w  w w .  j  av  a2 s.co  m
        /* PARSE XML RESPONSE... */
        // This is a really horrible tree-walk but it is, at least, NOT
        // vulnerable to the whitespace in the XML being reformatted.
        // After *much* debate, we decided that this is no worse than other
        // ways of doing this!
        Document d = getDSpaceProps(endpoint, base, 1);
        if (d == null)
            return null;

        // find multistatus node
        Node node_multistatus = null;
        NodeList nl = d.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j)
            if (nl.item(j).getNodeName() != null && nl.item(j).getNodeName().equals(LAYER1)) {
                node_multistatus = nl.item(j);
                break;
            }
        if (node_multistatus == null)
            return null;

        boolean foundMatch = false; // haven't found the named node so far
        DSpaceItemInfo dii = new DSpaceItemInfo(); // the return value
        // (unless we return
        // null)
        dii.displayname = needle; // will only be returned if we find the
        // name sought
        dii.endpoint = endpoint;

        // examine each response node, looking for ones which match the
        // string sought
        nl = node_multistatus.getChildNodes();
        for (int j = 0; j < nl.getLength(); ++j) {
            // only interested in nodes with name="response"
            if (nl.item(j).getNodeName() == null || !nl.item(j).getNodeName().equals(LAYER2))
                continue;
            Node node_response = nl.item(j);
            NodeList resources = node_response.getChildNodes();

            // grab the resource handle
            String handle = null;
            for (int k = 0; k < resources.getLength(); ++k)
                if (resources.item(k).getNodeName() != null && resources.item(k).getNodeName().equals(HREF)) {
                    handle = resources.item(k).getFirstChild().getNodeValue().trim();
                    break;
                }
            if (handle == null)
                continue; // skip this resource if it
            // doesn't have an 'href' node.

            // Communities and collections have a /-imploded handle
            // hierarchy.
            // The comm/coll's own handle is the last one.
            String[] handles = handle.split("/");
            handle = handles[handles.length - 1]; // only interested in
            // the last one
            if (!handle.startsWith("bitstream_")) // this only affects
                // reading bitstreams
                // when queryDSpaceFor
                // is called for a
                // resource
                dii.handle = handle.replace("%24", "/").substring(4);
            else {
                if (handles.length > 1)
                    dii.handle = handles[handles.length - 2].replace("%24", "/").substring(4);
                else
                    continue; // a handle containing only "bitstream_x" is
                // not valid
                try {
                    int indx;
                    String numberPart = handle.substring("bitstream_".length());
                    if ((indx = numberPart.indexOf(".")) != -1)
                        numberPart = numberPart.substring(0, indx);
                    dii.bitstreamID = Integer.parseInt(numberPart);
                } catch (NumberFormatException e) {
                }
            }

            // now loop over the child nodes again looking at propstat
            // blocks...
            for (int k = 0; k < resources.getLength(); ++k) {
                if (resources.item(k).getNodeName() == null || !resources.item(k).getNodeName().equals(LAYER3))
                    continue; // only
                // want
                // 'propstat'
                // nodes

                NodeList propstats = resources.item(k).getChildNodes();

                // first check whether status is OK (ignore all HTTP status
                // codes except 200)
                // no status node is assumed to mean OK. abort this propstat
                // if status is not OK.
                boolean status_ok = true;
                for (int l = 0; l < propstats.getLength(); ++l)
                    if (propstats.item(l).getNodeName() != null
                            && propstats.item(l).getNodeName().equals(STATUS)
                            && !propstats.item(l).getFirstChild().getNodeValue().trim().equals(ST_OK)) {
                        status_ok = false;
                        break;
                    }
                if (!status_ok)
                    continue; // skip this propstat node

                // Look for child nodes with name 'prop', having nested
                // child called 'displayname'.
                // This is only complicated when the base handle is a DSpace
                // resource. There will
                // be child nodes (with handle=bitstream_<n>) and the same
                // display name as the resource.
                // We need to extract properties from the bitstream_1 child
                // (.._2 is the license).
                for (int l = 0; l < propstats.getLength(); ++l) {
                    if (propstats.item(l).getNodeName() != null
                            && propstats.item(l).getNodeName().equals(LAYER4)) {
                        boolean recordFromThisChild = false;
                        String lastmod = null, contentlength = null, contenttype = null, dstype = null;
                        NodeList properties = propstats.item(l).getChildNodes();
                        for (int m = 0; m < properties.getLength(); ++m)
                            if (properties.item(m).getNodeName() != null) {
                                if (properties.item(m).getNodeName().equals(DISPNM) && properties.item(m)
                                        .getFirstChild().getNodeValue().trim().equals(needle)) {
                                    foundMatch = true;
                                    recordFromThisChild = true;
                                }
                                if (properties.item(m).getNodeName().equals(LSTMOD))
                                    lastmod = properties.item(m).getFirstChild().getNodeValue().trim();
                                if (properties.item(m).getNodeName().equals(CNTLEN))
                                    contentlength = properties.item(m).getFirstChild().getNodeValue().trim();
                                if (properties.item(m).getNodeName().equals(CNTTYP))
                                    contenttype = properties.item(m).getFirstChild().getNodeValue().trim();
                                if (properties.item(m).getNodeName().equals(DSTYPE)) {
                                    Node n = properties.item(m).getFirstChild();
                                    while (n != null) {
                                        String s = n.getNodeName();
                                        if (!s.equals("#text")) {
                                            dstype = s;
                                            break;
                                        }
                                        n = n.getNextSibling();
                                    }
                                }
                            }
                        if (recordFromThisChild) {
                            if (lastmod != null)
                                dii.lastmodified = lastmod;
                            if (contentlength != null)
                                try {
                                    dii.contentLength = Long.parseLong(contentlength);
                                } catch (NumberFormatException nfe) {
                                }
                            if (contenttype != null)
                                dii.contentType = contenttype;
                            if (dstype != null)
                                dii.itemType = dstype;
                            if (DSRESOURCES_AS_COLLECTIONS)
                                return dii;
                        }
                    }
                }
            }
        }
        if (foundMatch)
            return dii;
    } catch (Exception e) {
        log.warn("Error in CHH DSpace mechanism: parse error: [" + e.toString() + "]");
    }
    return null; // problem talking to DSpace or named resource has gone
}