Example usage for java.text DateFormat setTimeZone

List of usage examples for java.text DateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text DateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

public GWTMessageList retrieveMessages(String folderId, int start, int pageSize, String sortField, String dir,
        String[][] params) throws Exception {

    if (folderId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        UserAccount account = SessionManager.get().getUserAccount();
        log.debug("retrieving messages from " + folderId + " ...");

        try {/*from www .  ja  va  2s.  co  m*/
            IMailFolder currentFolder = mailbox.getMailFolderById(folderId);
            mailbox.setCurrentFolder(currentFolder);

            Message[] msgs = currentFolder.retrieveMessages(sortField);

            String quickSearchFields = MessageUtils.getParamValue(params, "fields");
            String extendedSearchFields = MessageUtils.getParamValue(params,
                    GWTMailConstants.EXTENDED_SEARCH_FIELDS);

            // all messages with only header data

            // quick search params
            if (quickSearchFields != null) {
                String quickSearchText = MessageUtils.getParamValue(params, "query");
                msgs = MessageUtils.quickFilterMessages(msgs, quickSearchFields, quickSearchText);
            } else if (extendedSearchFields != null) {
                msgs = MessageUtils.filterMessages(currentFolder, msgs, extendedSearchFields, params);
            }

            boolean ascending = "ASC".equals(dir);
            MessageUtils.sortMessages(msgs, sortField, ascending);

            if (msgs != null && msgs.length > 0) {
                log.debug("Building Array objects...");
                long time = System.currentTimeMillis();

                int total_count = msgs.length;
                start = Math.min(total_count - 1, start == -1 ? 0 : start);
                pageSize = pageSize == -1 ? account.getPreferences().getPageCount() : pageSize;
                pageSize = Math.min(pageSize, total_count - start);

                Message[] pagedMessages = new Message[pageSize];
                int pagedIndex = 0;
                for (int msgIndex = start; msgIndex < start + pageSize; msgIndex++) {
                    pagedMessages[pagedIndex++] = msgs[msgIndex];
                }
                FetchProfile completeProfile = MessageUtils.createFetchProfile(true, null);
                currentFolder.fetch(pagedMessages, completeProfile);

                String[][] messageStringArray = new String[pageSize][MessageListFields.values().length];
                Preferences preferences = SessionManager.get().getPreferences();

                // get date formats for message list date
                Locale locale = SessionManager.get().getLocale();
                TimeZone timezone = SessionManager.get().getTimeZone();
                String datePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_DATE_FORMAT_PATTERN, null, locale);
                String timePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_TIME_FORMAT_PATTERN, null, locale);

                NumberFormat sizeFormat = MessageUtils.createSizeFormat(locale);

                DateFormat dateFormat = null;
                DateFormat timeFormat = null;
                if (preferences.isShortTimeFormat()) {
                    dateFormat = new SimpleDateFormat(datePattern, locale);
                    timeFormat = new SimpleDateFormat(timePattern, locale);
                    timeFormat.setTimeZone(timezone);
                } else {
                    dateFormat = new SimpleDateFormat(datePattern + " " + timePattern, locale);
                }
                dateFormat.setTimeZone(timezone);
                Date today = Calendar.getInstance(timezone).getTime();

                for (int i = 0; i < pageSize; i++) {
                    if (preferences.isShortTimeFormat()
                            && DateUtils.isSameDay(today, pagedMessages[i].getSentDate())) {
                        // show only time
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                timeFormat, sizeFormat);
                    } else {
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                dateFormat, sizeFormat);
                    }
                }
                log.debug("..finish. Time for building Array: " + (System.currentTimeMillis() - time));

                return new GWTMessageList(messageStringArray, msgs.length);
            }

            return null;
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            throw new GWTMessageException(e.getMessage());
        }
    } else {
        return null;
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private void backupWallet(@Nonnull final String password) {
    File externalWalletBackupDir = new File(getFilesDir(), Constants.Files.EXTERNAL_WALLET_BACKUP_DIR);
    externalWalletBackupDir.mkdirs();/*from   w  ww .java2s . c om*/
    final DateFormat dateFormat = Iso8601Format.newDateFormat();
    dateFormat.setTimeZone(TimeZone.getDefault());
    final File file = new File(externalWalletBackupDir,
            Constants.Files.EXTERNAL_WALLET_BACKUP + "-" + dateFormat.format(new Date()));

    final Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet);

    Writer cipherOut = null;

    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        walletProto.writeTo(baos);
        baos.close();
        final byte[] plainBytes = baos.toByteArray();

        cipherOut = new OutputStreamWriter(new FileOutputStream(file), Constants.UTF_8);
        cipherOut.write(Crypto.encrypt(plainBytes, password.toCharArray()));
        cipherOut.flush();

        log.info("backed up wallet to: '" + file + "'");

        boolean maybeArchived = archiveWalletBackup(file);
        if (!maybeArchived)
            return;

        File[] allBackups = externalWalletBackupDir.listFiles();
        Arrays.sort(allBackups, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
            }
        });
        int backupsToDelete = allBackups.length - Constants.Files.EXTERNAL_WALLET_NUMBER_OF_BACKUPS_KEPT;
        for (int i = 0; i < backupsToDelete; i++) {
            log.info("removing old wallet backup '" + allBackups[i] + "'");
            allBackups[i].delete();
        }
    } catch (final IOException x) {
        final DialogBuilder dialog = DialogBuilder.warn(this, R.string.import_export_keys_dialog_failure_title);
        dialog.setMessage(getString(R.string.export_keys_dialog_failure, x.getMessage()));
        dialog.singleDismissButton(null);
        dialog.show();

        log.error("problem backing up wallet", x);
    } finally {
        try {
            cipherOut.close();
        } catch (final IOException x) {
            // swallow
        }
    }
}

From source file:com.vonglasow.michael.satstat.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            Context c = getApplicationContext();
            File dumpDir = c.getExternalFilesDir(null);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT);
            fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis())));

            File dumpFile = new File(dumpDir, fileName);
            PrintStream s;/*from w  ww  .  ja  va 2s  .c  o m*/
            try {
                InputStream buildInStream = getResources().openRawResource(R.raw.build);
                s = new PrintStream(dumpFile);
                s.append("SatStat build: ");

                int i;
                try {
                    i = buildInStream.read();
                    while (i != -1) {
                        s.write(i);
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(dumpFile);
                mediaScanIntent.setData(contentUri);
                c.sendBroadcast(mediaScanIntent);
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
    prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType);
    prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots);
    prefCoord = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord)));
    prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc);
    prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid);
    prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2);
    prefWifiSort = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort)));
    prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline);
    prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath);

    ActionBar actionBar = getSupportActionBar();

    setContentView(R.layout.activity_main);

    // Find out default screen orientation
    Configuration config = getResources().getConfiguration();
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    int rot = wm.getDefaultDisplay().getRotation();
    isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE
            && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180)
            || config.orientation == Configuration.ORIENTATION_PORTRAIT
                    && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270));
    Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen));

    // Create the adapter that will return a fragment for each of the
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme);
    mTabLayout = new TabLayout(ctx);
    LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    mTabLayout.setLayoutParams(mTabLayoutParams);

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        TabLayout.Tab newTab = mTabLayout.newTab();
        newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i));
        mTabLayout.addTab(newTab);
    }

    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(mTabLayout);

    mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

    // This is needed by the mapsforge library.
    AndroidGraphicFactory.createInstance(this.getApplication());

    // Get system services for event delivery
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}

From source file:org.projectforge.business.teamcal.event.model.TeamEventDO.java

/**
 * @param recurrenceExDate the recurrenceExDate to set
 * @return this for chaining.//from   ww w  .  j a  va 2 s .c  om
 */
@Transient
public TeamEventDO setRecurrenceDate(final Date recurrenceDate) {
    final DateFormat df = new SimpleDateFormat(DateFormats.ISO_TIMESTAMP_MILLIS);
    // Need the user's time-zone for getting midnight of desired date.
    df.setTimeZone(ThreadLocalUserContext.getTimeZone());
    // But print it as UTC date:
    final String recurrenceDateString = df.format(recurrenceDate);
    setRecurrenceDate(recurrenceDateString);
    return this;
}

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

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();/*from   w  w w  .j a va 2s .c  o  m*/

    JSONObject request = null;

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

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_DETAIL"), clientIpRaw));

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

            String lang = request.optString("language");
            JSONArray options = request.optJSONArray("options");
            if (options != null) {
                for (int i = 0; i < options.length(); i++) {
                    final String op = options.optString(i, null);
                    if (op != null) {
                        if (OPTION_WITH_KEYS.equals(op.toUpperCase(Locale.US))) {
                            optionWithKeys = true;
                        }
                    }
                }
            }

            // 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));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

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

            if (conn != null) {

                final Client client = new Client(conn);
                final Test test = new Test(conn);
                TestNdt ndt = new TestNdt(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {

                    if (!ndt.loadByTestId(test.getUid()))
                        ndt = null;

                    final Locale locale = new Locale(lang);
                    final Format format = new SignificantFormat(2, locale);

                    final JSONArray resultList = new JSONArray();

                    final JSONObject singleItem = addObject(resultList, "time");
                    final Field timeField = test.getField("time");
                    if (!timeField.isNull()) {
                        final Date date = ((TimestampField) timeField).getDate();
                        final long time = date.getTime();
                        singleItem.put("time", time); //csv 3

                        final Field timezoneField = test.getField("timezone");
                        if (!timezoneField.isNull()) {
                            final String tzString = timezoneField.toString();
                            final TimeZone tz = TimeZone.getTimeZone(timezoneField.toString());
                            singleItem.put("timezone", tzString);

                            final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                    DateFormat.MEDIUM, locale);
                            dateFormat.setTimeZone(tz);
                            singleItem.put("value", dateFormat.format(date));

                            final Format tzFormat = new DecimalFormat("+0.##;-0.##",
                                    new DecimalFormatSymbols(locale));

                            final float offset = tz.getOffset(time) / 1000f / 60f / 60f;
                            addString(resultList, "timezone", String.format("UTC%sh", tzFormat.format(offset)));
                        }
                    }

                    // speed download in Mbit/s (converted from kbit/s) - csv 10 (in kbit/s)
                    final Field downloadField = test.getField("speed_download");
                    if (!downloadField.isNull()) {
                        final String download = format.format(downloadField.doubleValue() / 1000d);
                        addString(resultList, "speed_download",
                                String.format("%s %s", download, labels.getString("RESULT_DOWNLOAD_UNIT")));
                    }

                    // speed upload im MBit/s (converted from kbit/s) - csv 11 (in kbit/s)
                    final Field uploadField = test.getField("speed_upload");
                    if (!uploadField.isNull()) {
                        final String upload = format.format(uploadField.doubleValue() / 1000d);
                        addString(resultList, "speed_upload",
                                String.format("%s %s", upload, labels.getString("RESULT_UPLOAD_UNIT")));
                    }

                    // median ping in ms
                    final Field pingMedianField = test.getField("ping_median");
                    if (!pingMedianField.isNull()) {
                        final String pingMedian = format.format(pingMedianField.doubleValue() / 1000000d);
                        addString(resultList, "ping_median",
                                String.format("%s %s", pingMedian, labels.getString("RESULT_PING_UNIT")));
                    }

                    // signal strength RSSI in dBm - csv 13
                    final Field signalStrengthField = test.getField("signal_strength");
                    if (!signalStrengthField.isNull())
                        addString(resultList, "signal_strength", String.format("%d %s",
                                signalStrengthField.intValue(), labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal strength RSRP in dBm (LTE) - csv 29
                    final Field lteRsrpField = test.getField("lte_rsrp");
                    if (!lteRsrpField.isNull())
                        addString(resultList, "signal_rsrp", String.format("%d %s", lteRsrpField.intValue(),
                                labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal quality in LTE, RSRQ in dB
                    final Field lteRsrqField = test.getField("lte_rsrq");
                    if (!lteRsrqField.isNull())
                        addString(resultList, "signal_rsrq", String.format("%d %s", lteRsrqField.intValue(),
                                labels.getString("RESULT_DB_UNIT")));

                    // network, eg. "3G (HSPA+)
                    //TODO fix helper-function
                    final Field networkTypeField = test.getField("network_type");
                    if (!networkTypeField.isNull())
                        addString(resultList, "network_type",
                                Helperfunctions.getNetworkTypeName(networkTypeField.intValue()));

                    // geo-location
                    JSONObject locationJson = getGeoLocation(this, test, settings, conn, labels);

                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            addString(resultList, "location", locationJson.getString("location"));
                        }
                        if (locationJson.has("country_location")) {
                            addString(resultList, "country_location",
                                    locationJson.getString("country_location"));
                        }
                        if (locationJson.has("motion")) {
                            addString(resultList, "motion", locationJson.getString("motion"));
                        }
                    }

                    // country derived from AS registry
                    final Field countryAsnField = test.getField("country_asn");
                    if (!countryAsnField.isNull())
                        addString(resultList, "country_asn", countryAsnField.toString());

                    // country derived from geo-IP database
                    final Field countryGeoipField = test.getField("country_geoip");
                    if (!countryGeoipField.isNull())
                        addString(resultList, "country_geoip", countryGeoipField.toString());

                    final Field zipCodeField = test.getField("zip_code");
                    if (!zipCodeField.isNull()) {
                        final String zipCode = zipCodeField.toString();
                        final int zipCodeInt = zipCodeField.intValue();
                        if (zipCodeInt > 999 || zipCodeInt <= 9999) // plausibility of zip code (must be 4 digits in Austria)
                            addString(resultList, "zip_code", zipCode);
                    }

                    final Field dataField = test.getField("data");
                    if (!Strings.isNullOrEmpty(dataField.toString())) {
                        final JSONObject data = new JSONObject(dataField.toString());

                        if (data.has("region"))
                            addString(resultList, "region", data.getString("region"));
                        if (data.has("municipality"))
                            addString(resultList, "municipality", data.getString("municipality"));
                        if (data.has("settlement"))
                            addString(resultList, "settlement", data.getString("settlement"));
                        if (data.has("whitespace"))
                            addString(resultList, "whitespace", data.getString("whitespace"));

                        if (data.has("cell_id"))
                            addString(resultList, "cell_id", data.getString("cell_id"));
                        if (data.has("cell_name"))
                            addString(resultList, "cell_name", data.getString("cell_name"));
                        if (data.has("cell_id_multiple") && data.getBoolean("cell_id_multiple"))
                            addString(resultList, "cell_id_multiple",
                                    getTranslation("value", "cell_id_multiple"));
                    }

                    final Field speedTestDurationField = test.getField("speed_test_duration");
                    if (!speedTestDurationField.isNull()) {
                        final String speedTestDuration = format
                                .format(speedTestDurationField.doubleValue() / 1000d);
                        addString(resultList, "speed_test_duration", String.format("%s %s", speedTestDuration,
                                labels.getString("RESULT_DURATION_UNIT")));
                    }

                    // public client ip (private)
                    addString(resultList, "client_public_ip", test.getField("client_public_ip"));

                    // AS number - csv 24
                    addString(resultList, "client_public_ip_as", test.getField("public_ip_asn"));

                    // name of AS
                    addString(resultList, "client_public_ip_as_name", test.getField("public_ip_as_name"));

                    // reverse hostname (from ip) - (private)
                    addString(resultList, "client_public_ip_rdns", test.getField("public_ip_rdns"));

                    // operator - derived from provider_id (only for pre-defined operators)
                    //TODO replace provider-information by more generic information
                    addString(resultList, "provider", test.getField("provider_id_name"));

                    // type of client local ip (private)
                    addString(resultList, "client_local_ip", test.getField("client_ip_local_type"));

                    // nat-translation of client - csv 23
                    addString(resultList, "nat_type", test.getField("nat_type"));

                    // wifi base station id SSID (numberic) eg 01:2c:3d..
                    addString(resultList, "wifi_ssid", test.getField("wifi_ssid"));
                    // wifi base station id - BSSID (text) eg 'my hotspot'
                    addString(resultList, "wifi_bssid", test.getField("wifi_bssid"));

                    // nominal link speed of wifi connection in MBit/s
                    final Field linkSpeedField = test.getField("wifi_link_speed");
                    if (!linkSpeedField.isNull())
                        addString(resultList, "wifi_link_speed", String.format("%s %s",
                                linkSpeedField.toString(), labels.getString("RESULT_WIFI_LINK_SPEED_UNIT")));
                    // name of mobile network operator (eg. 'T-Mobile AT')
                    addString(resultList, "network_operator_name", test.getField("network_operator_name"));

                    // mobile network name derived from MCC/MNC of network, eg. '232-01'
                    final Field networkOperatorField = test.getField("network_operator");

                    // mobile provider name, eg. 'Hutchison Drei' (derived from mobile_provider_id)
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (mobileProviderNameField.isNull()) // eg. '248-02'
                        addString(resultList, "network_operator", networkOperatorField);
                    else {
                        if (networkOperatorField.isNull())
                            addString(resultList, "network_operator", mobileProviderNameField);
                        else // eg. 'Hutchison Drei (232-10)'
                            addString(resultList, "network_operator",
                                    String.format("%s (%s)", mobileProviderNameField, networkOperatorField));
                    }

                    addString(resultList, "network_sim_operator_name",
                            test.getField("network_sim_operator_name"));

                    final Field networkSimOperatorField = test.getField("network_sim_operator");
                    final Field networkSimOperatorTextField = test
                            .getField("network_sim_operator_mcc_mnc_text");
                    if (networkSimOperatorTextField.isNull())
                        addString(resultList, "network_sim_operator", networkSimOperatorField);
                    else
                        addString(resultList, "network_sim_operator",
                                String.format("%s (%s)", networkSimOperatorTextField, networkSimOperatorField));

                    final Field roamingTypeField = test.getField("roaming_type");
                    if (!roamingTypeField.isNull())
                        addString(resultList, "roaming",
                                Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));

                    final long totalDownload = test.getField("total_bytes_download").longValue();
                    final long totalUpload = test.getField("total_bytes_upload").longValue();
                    final long totalBytes = totalDownload + totalUpload;
                    if (totalBytes > 0) {
                        final String totalBytesString = format.format(totalBytes / (1000d * 1000d));
                        addString(resultList, "total_bytes", String.format("%s %s", totalBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    // interface volumes - total including control-server and pre-tests (and other tests)
                    final long totalIfDownload = test.getField("test_if_bytes_download").longValue();
                    final long totalIfUpload = test.getField("test_if_bytes_upload").longValue();
                    // output only total of down- and upload
                    final long totalIfBytes = totalIfDownload + totalIfUpload;
                    if (totalIfBytes > 0) {
                        final String totalIfBytesString = format.format(totalIfBytes / (1000d * 1000d));
                        addString(resultList, "total_if_bytes", String.format("%s %s", totalIfBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // interface volumes during test
                    // download test - volume in download direction
                    final long testDlIfBytesDownload = test.getField("testdl_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testDlIfBytesDownloadString = format
                                .format(testDlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_download", String.format("%s %s",
                                testDlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // download test - volume in upload direction
                    final long testDlIfBytesUpload = test.getField("testdl_if_bytes_upload").longValue();
                    if (testDlIfBytesUpload > 0l) {
                        final String testDlIfBytesUploadString = format
                                .format(testDlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_upload", String.format("%s %s",
                                testDlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in upload direction
                    final long testUlIfBytesUpload = test.getField("testul_if_bytes_upload").longValue();
                    if (testUlIfBytesUpload > 0l) {
                        final String testUlIfBytesUploadString = format
                                .format(testUlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_upload", String.format("%s %s",
                                testUlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in download direction
                    final long testUlIfBytesDownload = test.getField("testul_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testUlIfBytesDownloadString = format
                                .format(testUlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_download", String.format("%s %s",
                                testUlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    //start time download-test 
                    final Field time_dl_ns = test.getField("time_dl_ns");
                    if (!time_dl_ns.isNull()) {
                        addString(resultList, "time_dl",
                                String.format("%s %s", format.format(time_dl_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration download-test 
                    final Field duration_download_ns = test.getField("nsec_download");
                    if (!duration_download_ns.isNull()) {
                        addString(resultList, "duration_dl",
                                String.format("%s %s",
                                        format.format(duration_download_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //start time upload-test 
                    final Field time_ul_ns = test.getField("time_ul_ns");
                    if (!time_ul_ns.isNull()) {
                        addString(resultList, "time_ul",
                                String.format("%s %s", format.format(time_ul_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration upload-test 
                    final Field duration_upload_ns = test.getField("nsec_upload");
                    if (!duration_upload_ns.isNull()) {
                        addString(resultList, "duration_ul",
                                String.format("%s %s",
                                        format.format(duration_upload_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    if (ndt != null) {
                        final String downloadNdt = format.format(ndt.getField("s2cspd").doubleValue());
                        addString(resultList, "speed_download_ndt",
                                String.format("%s %s", downloadNdt, labels.getString("RESULT_DOWNLOAD_UNIT")));

                        final String uploaddNdt = format.format(ndt.getField("c2sspd").doubleValue());
                        addString(resultList, "speed_upload_ndt",
                                String.format("%s %s", uploaddNdt, labels.getString("RESULT_UPLOAD_UNIT")));

                        // final String pingNdt =
                        // format.format(ndt.getField("avgrtt").doubleValue());
                        // addString(resultList, "ping_ndt",
                        // String.format("%s %s", pingNdt,
                        // labels.getString("RESULT_PING_UNIT")));
                    }

                    addString(resultList, "server_name", test.getField("server_name"));
                    addString(resultList, "plattform", test.getField("plattform"));
                    addString(resultList, "os_version", test.getField("os_version"));
                    addString(resultList, "model", test.getField("model_fullname"));
                    addString(resultList, "client_name", test.getField("client_name"));
                    addString(resultList, "client_software_version", test.getField("client_software_version"));
                    final String encryption = test.getField("encryption").toString();

                    if (encryption != null) {
                        addString(resultList, "encryption",
                                "NONE".equals(encryption) ? labels.getString("key_encryption_false")
                                        : labels.getString("key_encryption_true"));
                    }

                    addString(resultList, "client_version", test.getField("client_version"));

                    addString(resultList, "duration", String.format("%d %s",
                            test.getField("duration").intValue(), labels.getString("RESULT_DURATION_UNIT")));

                    // number of threads for download-test
                    final Field num_threads = test.getField("num_threads");
                    if (!num_threads.isNull()) {
                        addInt(resultList, "num_threads", num_threads);
                    }

                    //number of threads for upload-test
                    final Field num_threads_ul = test.getField("num_threads_ul");
                    if (!num_threads_ul.isNull()) {
                        addInt(resultList, "num_threads_ul", num_threads_ul);
                    }

                    //dz 2013-11-09 removed UUID from details as users might get confused by two
                    //              ids;
                    //addString(resultList, "uuid", String.format("T%s", test.getField("uuid")));

                    final Field openTestUUIDField = test.getField("open_test_uuid");
                    if (!openTestUUIDField.isNull())
                        addString(resultList, "open_test_uuid", String.format("O%s", openTestUUIDField));

                    //number of threads for upload-test
                    final Field tag = test.getField("tag");
                    if (!tag.isNull()) {
                        addString(resultList, "tag", tag);
                    }

                    if (ndt != null) {
                        addString(resultList, "ndt_details_main", ndt.getField("main"));
                        addString(resultList, "ndt_details_stat", ndt.getField("stat"));
                        addString(resultList, "ndt_details_diag", ndt.getField("diag"));
                    }

                    if (resultList.length() == 0)
                        errorList.addError("ERROR_DB_GET_TESTRESULT_DETAIL");

                    answer.put("testresultdetail", resultList);
                } else
                    errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } 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_TESTRESULT_DETAIL_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:org.apache.archiva.rest.services.DefaultRepositoriesService.java

@Override
public Boolean deleteArtifact(Artifact artifact) throws ArchivaRestServiceException {

    String repositoryId = artifact.getContext();
    // some rest call can use context or repositoryId
    // so try both!!
    if (StringUtils.isEmpty(repositoryId)) {
        repositoryId = artifact.getRepositoryId();
    }/*from  w  w w.j  a va 2  s  .co  m*/
    if (StringUtils.isEmpty(repositoryId)) {
        throw new ArchivaRestServiceException("repositoryId cannot be null", 400, null);
    }

    if (!isAuthorizedToDeleteArtifacts(repositoryId)) {
        throw new ArchivaRestServiceException("not authorized to delete artifacts", 403, null);
    }

    if (artifact == null) {
        throw new ArchivaRestServiceException("artifact cannot be null", 400, null);
    }

    if (StringUtils.isEmpty(artifact.getGroupId())) {
        throw new ArchivaRestServiceException("artifact.groupId cannot be null", 400, null);
    }

    if (StringUtils.isEmpty(artifact.getArtifactId())) {
        throw new ArchivaRestServiceException("artifact.artifactId cannot be null", 400, null);
    }

    // TODO more control on artifact fields

    boolean snapshotVersion = VersionUtil.isSnapshot(artifact.getVersion())
            | VersionUtil.isGenericSnapshot(artifact.getVersion());

    RepositorySession repositorySession = repositorySessionFactory.createSession();
    try {
        Date lastUpdatedTimestamp = Calendar.getInstance().getTime();

        TimeZone timezone = TimeZone.getTimeZone("UTC");
        DateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss");
        fmt.setTimeZone(timezone);
        ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository(repositoryId);

        VersionedReference ref = new VersionedReference();
        ref.setArtifactId(artifact.getArtifactId());
        ref.setGroupId(artifact.getGroupId());
        ref.setVersion(artifact.getVersion());

        ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent(repositoryId);

        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setArtifactId(artifact.getArtifactId());
        artifactReference.setGroupId(artifact.getGroupId());
        artifactReference.setVersion(artifact.getVersion());
        artifactReference.setClassifier(artifact.getClassifier());
        artifactReference.setType(artifact.getPackaging());

        MetadataRepository metadataRepository = repositorySession.getRepository();

        String path = repository.toMetadataPath(ref);

        if (StringUtils.isNotBlank(artifact.getClassifier())) {
            if (StringUtils.isBlank(artifact.getPackaging())) {
                throw new ArchivaRestServiceException(
                        "You must configure a type/packaging when using classifier", 400, null);
            }

            repository.deleteArtifact(artifactReference);

        } else {

            int index = path.lastIndexOf('/');
            path = path.substring(0, index);
            File targetPath = new File(repoConfig.getLocation(), path);

            if (!targetPath.exists()) {
                //throw new ContentNotFoundException(
                //    artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
                log.warn("targetPath {} not found skip file deletion", targetPath);
            }

            // TODO: this should be in the storage mechanism so that it is all tied together
            // delete from file system
            if (!snapshotVersion) {
                repository.deleteVersion(ref);
            } else {
                Set<ArtifactReference> related = repository.getRelatedArtifacts(artifactReference);
                log.debug("related: {}", related);
                for (ArtifactReference artifactRef : related) {
                    repository.deleteArtifact(artifactRef);
                }
            }
            File metadataFile = getMetadata(targetPath.getAbsolutePath());
            ArchivaRepositoryMetadata metadata = getMetadata(metadataFile);

            updateMetadata(metadata, metadataFile, lastUpdatedTimestamp, artifact);
        }
        Collection<ArtifactMetadata> artifacts = Collections.emptyList();

        if (snapshotVersion) {
            String baseVersion = VersionUtil.getBaseVersion(artifact.getVersion());
            artifacts = metadataRepository.getArtifacts(repositoryId, artifact.getGroupId(),
                    artifact.getArtifactId(), baseVersion);
        } else {
            artifacts = metadataRepository.getArtifacts(repositoryId, artifact.getGroupId(),
                    artifact.getArtifactId(), artifact.getVersion());
        }

        log.debug("artifacts: {}", artifacts);

        if (artifacts.isEmpty()) {
            if (!snapshotVersion) {
                // verify metata repository doesn't contains anymore the version
                Collection<String> projectVersions = metadataRepository.getProjectVersions(repositoryId,
                        artifact.getGroupId(), artifact.getArtifactId());

                if (projectVersions.contains(artifact.getVersion())) {
                    log.warn("artifact not found when deleted but version still here ! so force cleanup");
                    metadataRepository.removeProjectVersion(repositoryId, artifact.getGroupId(),
                            artifact.getArtifactId(), artifact.getVersion());
                }

            }
        }

        for (ArtifactMetadata artifactMetadata : artifacts) {

            // TODO: mismatch between artifact (snapshot) version and project (base) version here
            if (artifactMetadata.getVersion().equals(artifact.getVersion())) {
                if (StringUtils.isNotBlank(artifact.getClassifier())) {
                    if (StringUtils.isBlank(artifact.getPackaging())) {
                        throw new ArchivaRestServiceException(
                                "You must configure a type/packaging when using classifier", 400, null);
                    }
                    // cleanup facet which contains classifier information
                    MavenArtifactFacet mavenArtifactFacet = (MavenArtifactFacet) artifactMetadata
                            .getFacet(MavenArtifactFacet.FACET_ID);

                    if (StringUtils.equals(artifact.getClassifier(), mavenArtifactFacet.getClassifier())) {
                        artifactMetadata.removeFacet(MavenArtifactFacet.FACET_ID);
                        String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(),
                                version = artifact.getVersion();
                        MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
                        mavenArtifactFacetToCompare.setClassifier(artifact.getClassifier());
                        metadataRepository.removeArtifact(repositoryId, groupId, artifactId, version,
                                mavenArtifactFacetToCompare);
                        metadataRepository.save();
                    }

                } else {
                    if (snapshotVersion) {
                        metadataRepository.removeArtifact(artifactMetadata,
                                VersionUtil.getBaseVersion(artifact.getVersion()));
                    } else {
                        metadataRepository.removeArtifact(artifactMetadata.getRepositoryId(),
                                artifactMetadata.getNamespace(), artifactMetadata.getProject(),
                                artifact.getVersion(), artifactMetadata.getId());
                    }
                }
                // TODO: move into the metadata repository proper - need to differentiate attachment of
                //       repository metadata to an artifact
                for (RepositoryListener listener : listeners) {
                    listener.deleteArtifact(metadataRepository, repository.getId(),
                            artifactMetadata.getNamespace(), artifactMetadata.getProject(),
                            artifactMetadata.getVersion(), artifactMetadata.getId());
                }

                triggerAuditEvent(repositoryId, path, AuditEvent.REMOVE_FILE);
            }
        }
    } catch (ContentNotFoundException e) {
        throw new ArchivaRestServiceException("Artifact does not exist: " + e.getMessage(), 400, e);
    } catch (RepositoryNotFoundException e) {
        throw new ArchivaRestServiceException("Target repository cannot be found: " + e.getMessage(), 400, e);
    } catch (RepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (MetadataResolutionException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (MetadataRepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException("RepositoryAdmin exception: " + e.getMessage(), 500, e);
    } finally {

        repositorySession.save();

        repositorySession.close();
    }
    return Boolean.TRUE;
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

public long getTimeDiff() {
    String time = null;//ww  w.  j a  va 2s.com
    String tzid = null;
    try {

        String req = configLoader.getServerProperty(Def.SERVER_URI) + "/config/time";

        String response = sendGetRequest(req, 0, 0);
        if (log.isTraceEnabled()) {
            log.trace("RESPONSE getTime: \n" + response);
        }
        JSONObject jo = JSONObject.fromObject(response);
        JSONObject jdata = jo.getJSONObject("data");

        // it should be in Local time US/Central but it return the 'Z' at the end
        time = jdata.getString("time");

        tzid = jdata.getString("tzid");

        //DateFormat f = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        DateFormat f = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
        f.setTimeZone(TimeZone.getTimeZone(tzid));//("CST")); 
        Date d = f.parse(time);

        long fmTime = d.getTime();

        long myTime = configLoader.getServerTime(System.currentTimeMillis());

        return Math.abs(fmTime - myTime);

    } catch (Exception e) {
        if (!errorOnGetTimeNotified) {
            log.error("Error getting time, not supported!", e);
            errorOnGetTimeNotified = true;
        }
        return 0;
    }

}

From source file:com.openddal.test.BaseTestCase.java

/**
 * Check if two values are equal, and if not throw an exception.
 *
 * @param expected the expected value//from ww w. j a  v  a2  s.  c  o  m
 * @param actual the actual value
 * @throws AssertionError if the values are not equal
 */
public void assertEquals(java.util.Date expected, java.util.Date actual) {
    if (expected != actual && !expected.equals(actual)) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        SimpleTimeZone gmt = new SimpleTimeZone(0, "Z");
        df.setTimeZone(gmt);
        fail("Expected: " + df.format(expected) + " actual: " + df.format(actual));
    }
}

From source file:com.kncwallet.wallet.ui.WalletActivity.java

private void exportPrivateKeys(@Nonnull final String password) {
    try {//  w w  w . j av a  2  s  .  c  om
        Constants.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();
        final DateFormat dateFormat = Iso8601Format.newDateFormat();
        dateFormat.setTimeZone(TimeZone.getDefault());
        final File file = new File(Constants.EXTERNAL_WALLET_BACKUP_DIR,
                Constants.EXTERNAL_WALLET_KEY_BACKUP + "-" + dateFormat.format(new Date()));

        final List<ECKey> keys = new LinkedList<ECKey>();
        for (final ECKey key : wallet.getKeys())
            if (!wallet.isKeyRotating(key))
                keys.add(key);

        final StringWriter plainOut = new StringWriter();
        WalletUtils.writeKeys(plainOut, keys);
        plainOut.close();
        final String plainText = plainOut.toString();

        final String cipherText = Crypto.encrypt(plainText, password.toCharArray());

        final Writer cipherOut = new OutputStreamWriter(new FileOutputStream(file), Constants.UTF_8);
        cipherOut.write(cipherText);
        cipherOut.close();

        final AlertDialog.Builder dialog = new KnCDialog.Builder(this).setInverseBackgroundForced(true)
                .setMessage(getString(R.string.export_keys_dialog_success, file));
        dialog.setPositiveButton(R.string.export_keys_dialog_button_archive, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                mailPrivateKeys(file);
            }
        });
        dialog.setNegativeButton(R.string.button_dismiss, null);
        dialog.show();

        log.info("exported " + keys.size() + " private keys to " + file);
    } catch (final IOException x) {
        new KnCDialog.Builder(this).setInverseBackgroundForced(true).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.import_export_keys_dialog_failure_title)
                .setMessage(getString(R.string.export_keys_dialog_failure, x.getMessage()))
                .setNeutralButton(R.string.button_dismiss, null).show();

        log.error("problem writing private keys", x);
    }
}

From source file:com.krawler.spring.crm.common.crmManagerDAOImpl.java

public String preferenceDatejsformat(String timeZoneDiff, Date date, DateFormat sdf) throws ServiceException {
    String result = "";
    try {/*from w w w .ja va  2 s.  c  o  m*/
        sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff));
        String prefDate = "";
        if (date != null) {
            result = sdf.format(date);
        } else {
            return result;
        }
    } catch (Exception e) {
        throw ServiceException.FAILURE("crmManagerDAOImpl.preferenceDate", e);
    }
    return result;
}