Example usage for java.util TimeZone getDefault

List of usage examples for java.util TimeZone getDefault

Introduction

In this page you can find the example usage for java.util TimeZone getDefault.

Prototype

public static TimeZone getDefault() 

Source Link

Document

Gets the default TimeZone of the Java virtual machine.

Usage

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testNamedJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    NamedBean bean = new NamedBean();
    bean.setBooleanValue(true);/*from  w w  w .  j a  v a  2  s .  co  m*/
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("testNamedBean"));
    json = json.getJSONObject("testNamedBean");

    assertEquals(true, json.getBoolean("testBooleanValue"));
    assertEquals(0.451, json.getDouble("testDoubleValue"));
    assertEquals(1.34f, (float) json.getDouble("testFloatValue"));
    assertEquals(3400100, json.getInt("testIntValue"));
    assertEquals(3400100200L, json.getLong("testLongValue"));
    assertEquals(32767, (short) json.getInt("testShortValue"));
    assertEquals("String", json.getString("testStringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue"));

    assertTrue(json.has("testBeanValue"));
    JSONObject inBeanJson = json.getJSONObject("testBeanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("testStringListValue"));
    JSONArray stringListJson = json.getJSONArray("testStringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("testBeanListValue"));
    JSONArray beanListJson = json.getJSONArray("testBeanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:info.magnolia.cms.core.MetaData.java

/**
 * Part of metadata, adds activated date of the current node
 *///from  w ww. ja v a  2  s. c om
public void setLastActivationActionDate() throws AccessDeniedException {
    allowUpdate();
    Calendar value = new GregorianCalendar(TimeZone.getDefault());
    setProperty(this.getInternalPropertyName(LAST_ACTION), value);
}

From source file:io.ionic.links.IonicDeeplink.java

private int getTimeZoneOffset() {
    TimeZone tz = TimeZone.getDefault();
    return tz.getOffset(new Date().getTime()) / 1000 / 60;
}

From source file:com.arantius.tivocommander.Person.java

private void requestFinished() {
    if (--mOutstandingRequests > 0) {
        return;/* w w  w . j  a va2 s .c o  m*/
    }
    setProgressBarIndeterminateVisibility(false);

    if (mPerson == null || mCredits == null) {
        setContentView(R.layout.no_results);
        return;
    }

    setContentView(R.layout.list_person);

    // Credits.
    JsonNode[] credits = new JsonNode[mCredits.size()];
    int i = 0;
    for (JsonNode credit : mCredits) {
        credits[i++] = credit;
    }

    ListView lv = getListView();
    CreditsAdapter adapter = new CreditsAdapter(Person.this, R.layout.item_person_credits, credits);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(mOnItemClickListener);

    // Name.
    ((TextView) findViewById(R.id.person_name)).setText(mName);

    // Role.
    JsonNode rolesNode = mPerson.path("roleForPersonId");
    String[] roles = new String[rolesNode.size()];
    for (i = 0; i < rolesNode.size(); i++) {
        roles[i] = rolesNode.path(i).asText();
        roles[i] = Utils.ucFirst(roles[i]);
    }
    ((TextView) findViewById(R.id.person_role)).setText(Utils.join(", ", roles));

    // Birth date.
    TextView birthdateView = ((TextView) findViewById(R.id.person_birthdate));
    if (mPerson.has("birthDate")) {
        Date birthdate = Utils.parseDateStr(mPerson.path("birthDate").asText());
        SimpleDateFormat dateFormatter = new SimpleDateFormat("MMMMM d, yyyy", Locale.US);
        dateFormatter.setTimeZone(TimeZone.getDefault());
        Spannable birthdateStr = new SpannableString("Birthdate: " + dateFormatter.format(birthdate));
        birthdateStr.setSpan(new ForegroundColorSpan(Color.WHITE), 11, birthdateStr.length(), 0);
        birthdateView.setText(birthdateStr);
    } else {
        birthdateView.setVisibility(View.GONE);
    }

    // Birth place.
    TextView birthplaceView = ((TextView) findViewById(R.id.person_birthplace));
    if (mPerson.has("birthPlace")) {
        Spannable birthplaceStr = new SpannableString("Birthplace: " + mPerson.path("birthPlace").asText());
        birthplaceStr.setSpan(new ForegroundColorSpan(Color.WHITE), 12, birthplaceStr.length(), 0);
        birthplaceView.setText(birthplaceStr);
    } else {
        birthplaceView.setVisibility(View.GONE);
    }

    ImageView iv = (ImageView) findViewById(R.id.person_image);
    View pv = findViewById(R.id.person_image_progress);
    String imgUrl = Utils.findImageUrl(mPerson);
    new DownloadImageTask(this, iv, pv).execute(imgUrl);
}

From source file:de.micromata.genome.gwiki.controls.GWikiRegisterUserActionBean.java

protected boolean doRegister() {
    if (StringUtils.isBlank(catchaInput) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.nocatcha", "catchaInput");
        return false;
    }/*from  www .j  a v  a  2 s  . co m*/
    if (checkCatcha() == false) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.wrongcatcha", "catchaInput");
        return false;
    }
    user = StringUtils.trim(user);
    if (StringUtils.isBlank(user) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userempty", "user");
        return false;
    }
    email = StringUtils.trim(email);
    if (StringUtils.isBlank(email) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailempty", "email");
        return false;
    }
    if (checkEmail(email) == false) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailnotvalid", "email");
        return false;
    }
    if (doubleOptIn == false) {
        if (StringUtils.isBlank(pass) == true) {
            wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passempty", "pass");
            pass2 = "";
            return false;
        }
        if (pass.equals(pass2) == false) {
            wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passnotequal", "pass");
            return false;
        }
    } else {
        pass = GWikiLoginActionBean.genPassword();
    }

    GWikiAuthorizationExt authExt = (GWikiAuthorizationExt) wikiContext.getWikiWeb().getAuthorization();
    if (authExt.hasUser(wikiContext, user) == true) {
        wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userexists", "user");
        return false;
    }
    if (GWikiSimpleUserAuthorization.rankPasswort(pass) < 1000) {
        wikiContext.addValidationFieldError("gwiki.profile.message.password_too_simple", "pass");
        return false;
    }
    String cp = GWikiSimpleUserAuthorization.encrypt(pass);
    GWikiProps props = new GWikiProps();
    GWikiElement registeredUser = wikiContext.getWikiWeb().findElement("admin/user/registereduser");
    if (registeredUser != null) {
        props = new GWikiProps(((GWikiPropsArtefakt) registeredUser.getMainPart()).getCompiledObject());
    }
    props.setStringValue(GWikiAuthorizationExt.USER_PROP_EMAIL, email);
    if (props.getStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, null) == null) {
        props.setStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, "GWIKI_VIEWPAGES");
    }
    props.setStringValue(GWikiAuthorizationExt.USER_PROP_PASSWORD, cp);
    Locale loc = wikiContext.getRequest().getLocale();
    GWikiGlobalConfig gc = wikiContext.getWikiWeb().getWikiConfig();

    if (loc != null) {
        String lang = loc.getLanguage();
        if (gc.getAvailableLanguages(wikiContext).contains(lang) == true) {
            props.setStringValue(GWikiAuthorizationExt.USER_LANG, lang);
        }
    }
    if (StringUtils.isEmpty(clientTzOffset) == false) {
        try {
            int offsetMin = Integer.parseInt(clientTzOffset);
            int daysaving = TimeZone.getDefault().getDSTSavings();
            int offsetMs = (offsetMin * 1000 * 60 * -1) - daysaving;
            int offsetHour = ((offsetMin / 60) * -1) - (daysaving / ((int) TimeInMillis.HOUR));
            String tzs = "Etc/GMT";
            if (offsetHour != 0) {
                if (offsetHour > 0) {
                    tzs += "+";
                }
                tzs += offsetHour;
            }
            List<String> tcs = gc.getAvailableTimeZones(wikiContext);
            if (tcs.contains(tzs) == true) {
                props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzs);
            } else {
                // String[] offsets = TimeZone.getAvailableIDs(offsetMs);

                for (String tzss : tcs) {
                    TimeZone tz = TimeZone.getTimeZone(tzss);
                    int rawo = tz.getOffset(System.currentTimeMillis());
                    if (rawo == offsetMs) {
                        props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzss);
                        break;
                    }
                }
            }
        } catch (NumberFormatException ex) {
            // ignore
        }
    }
    if (authExt.createUser(wikiContext, user, props) == false) {
        wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.internalerrorstore");
        return false;
    }
    if (doubleOptIn == true) {
        try {
            GWikiLoginActionBean.sendPasswordToUser(wikiContext, user, email, pass);

            wikiContext.addValidationError("gwiki.page.admin.Login.message.resetpassw.emailsent");
        } catch (Exception ex) {
            GWikiLog.error("Cannot send register email: " + ex.getMessage(), ex);
            wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.unabletosend");
        }
        showForm = false;
    } else {
        boolean success = wikiContext.getWikiWeb().getAuthorization().login(wikiContext, StringUtils.trim(user),
                StringUtils.trim(pass));
        if (success == false) {
            return false;
        }
    }
    return true;
}

From source file:net.sourceforge.eclipsetrader.yahoo.Feed.java

private void update() {
    // Builds the url for quotes download
    String host = "quote.yahoo.com"; //$NON-NLS-1$
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); //$NON-NLS-1$ //$NON-NLS-2$
    for (Iterator iter = map.values().iterator(); iter.hasNext();)
        url = url.append((String) iter.next() + "+"); //$NON-NLS-1$
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap"); //$NON-NLS-1$
    log.debug(url.toString());//from   w  w  w  . java2s. com

    // Read the last prices
    String line = ""; //$NON-NLS-1$
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(","); //$NON-NLS-1$
            if (line.indexOf(";") != -1) //$NON-NLS-1$
                item = line.split(";"); //$NON-NLS-1$

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US); //$NON-NLS-1$
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1) //$NON-NLS-1$
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1) //$NON-NLS-1$
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                log.error(e.getMessage() + ": " + line); //$NON-NLS-1$
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase((String) map.get(security))) {
                    security.setQuote(quote, open, high, low, close);
                }
            }
        }
        in.close();
    } catch (Exception e) {
        log.error(e);
    }
}

From source file:com.duroty.application.files.manager.SearchManager.java

/**
 * DOCUMENT ME!/* w  w  w .ja  v a 2s  .c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param token DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param messagesByPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param orderType DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws FilesException DOCUMENT ME!
 */
public SearchObj simple(Session hsession, String repositoryName, String token, String folderName, int label,
        int page, int messagesByPage, int order, String orderType) throws FilesException {
    String lucenePathMessages = null;

    if (!defaultLucenePath.endsWith(File.separator)) {
        lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    } else {
        lucenePathMessages = defaultLucenePath + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    }

    Searcher searcher = null;
    SearchObj searchObj = new SearchObj();
    Sort sort = null;

    try {
        Users user = getUser(hsession, repositoryName);
        Locale locale = new Locale(user.getUseLanguage());
        TimeZone timeZone = TimeZone.getDefault();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance(timeZone, locale);
        calendar.setTime(now);

        SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale);
        SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale);

        searcher = MailIndexer.getSearcher(lucenePathMessages);

        Query query = null;

        if (!StringUtils.isBlank(folderName) && folderName.equals(this.folderFiles)) {
            BooleanQuery booleanQuery = new BooleanQuery();

            QueryParser parser = new QueryParser(Field_subject, analyzer);
            parser.setDefaultOperator(Operator.AND);

            Query aux1 = parser.parse("Files-System");
            booleanQuery.add(aux1, BooleanClause.Occur.MUST);

            Query aux2 = SimpleQueryParser.parse(token, analyzer);
            booleanQuery.add(aux2, BooleanClause.Occur.MUST);

            /*QueryParser parser2 = new QueryParser(Field_attachments, analyzer);
            parser2.setDefaultOperator(Operator.AND); 
            Query aux3 = parser2.parse("Message Text");
            booleanQuery.add(aux3, BooleanClause.Occur.MUST_NOT);*/

            query = booleanQuery;
        } else {
            /*BooleanQuery booleanQuery = new BooleanQuery();
                    
            QueryParser parser = new QueryParser(Field_attachments, analyzer);
             parser.setDefaultOperator(Operator.AND);                
                    
            Query aux1 = parser.parse("Message Text");
             booleanQuery.add(aux1, BooleanClause.Occur.MUST_NOT);
                    
            Query aux2 = SimpleQueryParser.parse(token, analyzer);
            booleanQuery.add(aux2, BooleanClause.Occur.MUST);
                    
            query = booleanQuery;*/

            query = SimpleQueryParser.parse(token, analyzer);
        }

        Hits hits = null;

        Date searchStart = new Date();

        boolean reverse = true;

        if (orderType.equals("ASC")) {
            reverse = false;
        } else {
            reverse = true;
        }

        switch (order) {
        case ORDER_BY_SIZE:
            sort = new Sort(new SortField[] { new SortField(Field_size, SortField.STRING, reverse),
                    SortField.FIELD_SCORE });

            break;

        case ORDER_BY_DATE:
            sort = new Sort(new SortField[] { new SortField(Field_lastDate, SortField.STRING, reverse),
                    SortField.FIELD_SCORE });

            break;

        default:
            sort = new Sort(new SortField[] { new SortField(null, SortField.SCORE, !reverse) });

            break;
        }

        ChainedFilter chained = null;

        if (label > 0) {
            chained = getChainedFilter(hsession, repositoryName, label);
        }

        if (chained != null) {
            hits = searcher.search(query, chained, sort);
        } else {
            hits = searcher.search(query, sort);
        }

        Date searchEnd = new Date();

        //time in seconds
        double time = ((double) (searchEnd.getTime() - searchStart.getTime())) / (double) 1000;

        int hitsLength = hits.length();

        if (hitsLength <= 0) {
            return null;
        }

        int start = page * messagesByPage;
        int end = start + messagesByPage;

        if (end > 0) {
            end = Math.min(hitsLength, end);
        } else {
            end = hitsLength;
        }

        if (start > end) {
            throw new SearchException("Search index of bound. start > end");
        }

        Vector files = new Vector();

        for (int j = start; j < end; j++) {
            Document doc = hits.doc(j);

            if (doc != null) {
                LuceneMessage lmsg = new LuceneMessage(doc);

                Message message = getMessage(hsession, repositoryName, lmsg.getIdint());

                if (message != null) {
                    Set set = message.getAttachments();
                    if (set != null) {
                        Iterator it = set.iterator();

                        while (it.hasNext()) {
                            Attachment attachment = (Attachment) it.next();

                            String name = attachment.getAttName();
                            if (!StringUtils.isBlank(name) && !name.equals("Message Text")) {
                                AttachmentObj obj = new AttachmentObj();
                                obj.setContentType(attachment.getAttContentType());

                                obj.setScore((int) (hits.score(j) * 100));

                                Date date = message.getMesDate();

                                if (date != null) {
                                    Calendar calendar2 = Calendar.getInstance(timeZone, locale);
                                    calendar2.setTime(date);

                                    if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))
                                            && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH))
                                            && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) {
                                        obj.setDateStr(formatter2.format(calendar2.getTime()));
                                    } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
                                        obj.setDateStr(formatter1.format(calendar2.getTime()));
                                    } else {
                                        obj.setDateStr(formatter3.format(calendar2.getTime()));
                                    }
                                }

                                obj.setDate(date);

                                obj.setDate(date);
                                obj.setIdint(attachment.getAttIdint());
                                obj.setName(attachment.getAttName());
                                obj.setPart(attachment.getAttPart());

                                int size = attachment.getAttSize();
                                size /= 1024;

                                if (size > 1024) {
                                    size /= 1024;
                                    obj.setSize(size + " MB");
                                } else {
                                    obj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
                                }

                                String extension = (String) this.extensions.get(attachment.getAttContentType());

                                if (StringUtils.isBlank(extension)) {
                                    extension = "generic";
                                }

                                obj.setExtension(extension);

                                if (message.isMesFlagged()) {
                                    obj.setFlagged(true);
                                } else {
                                    obj.setFlagged(false);
                                }

                                if (message.getLabMeses() != null) {
                                    Iterator it2 = message.getLabMeses().iterator();
                                    StringBuffer lab = new StringBuffer();

                                    while (it2.hasNext()) {
                                        if (lab.length() > 0) {
                                            lab.append(", ");
                                        }

                                        LabMes labMes = (LabMes) it2.next();
                                        lab.append(labMes.getId().getLabel().getLabName());
                                    }

                                    if (lab.length() > 0) {
                                        obj.setLabel(lab.toString());
                                    } else {
                                    }
                                }

                                obj.setBox(message.getMesBox());

                                obj.setMid(message.getMesName());

                                files.addElement(obj);
                            }
                        }
                    }
                }
            }
        }

        searchObj.setHits(hitsLength);
        searchObj.setTime(time);
        searchObj.setFiles(files);
    } catch (Exception ex) {
        throw new FilesException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }

    return searchObj;
}

From source file:com.google.android.apps.muzei.featuredart.FeaturedArtSource.java

@Override
protected void onTryUpdate(int reason) throws RetryException {
    Artwork currentArtwork = getCurrentArtwork();
    Artwork artwork;//from   w w  w  .  j  a  va 2  s.  c o m
    JSONObject jsonObject;
    try {
        jsonObject = IOUtil.fetchJsonObject(QUERY_URL);
        artwork = Artwork.fromJson(jsonObject);
    } catch (JSONException e) {
        LOGE(TAG, "Error reading JSON", e);
        throw new RetryException(e);
    } catch (IOException e) {
        LOGE(TAG, "Error reading JSON", e);
        throw new RetryException(e);
    }

    if (artwork != null && currentArtwork != null && artwork.getImageUri() != null
            && artwork.getImageUri().equals(currentArtwork.getImageUri())) {
        LOGD(TAG, "Skipping update of same artwork.");
    } else {
        LOGD(TAG, "Publishing artwork update: " + artwork);
        if (artwork != null && jsonObject != null) {
            publishArtwork(artwork);
        }
    }

    Date nextTime = null;
    String nextTimeStr = jsonObject.optString("nextTime");
    if (!TextUtils.isEmpty(nextTimeStr)) {
        int len = nextTimeStr.length();
        if (len > 4 && nextTimeStr.charAt(len - 3) == ':') {
            nextTimeStr = nextTimeStr.substring(0, len - 3) + nextTimeStr.substring(len - 2);
        }
        try {
            nextTime = sDateFormatTZ.parse(nextTimeStr);
        } catch (ParseException ignored) {
            try {
                sDateFormatLocal.setTimeZone(TimeZone.getDefault());
                nextTime = sDateFormatLocal.parse(nextTimeStr);
            } catch (ParseException e) {
                LOGE(TAG, "Can't schedule update; " + "invalid date format '" + nextTimeStr + "'", e);
            }
        }
    }

    boolean scheduleFallback = true;
    if (nextTime != null) {
        // jitter by up to N milliseconds
        scheduleUpdate(nextTime.getTime() + sRandom.nextInt(MAX_JITTER_MILLIS));
        scheduleFallback = false;
    }

    if (scheduleFallback) {
        // No next time, default to checking in 12 hours
        scheduleUpdate(System.currentTimeMillis() + 12 * 60 * 60 * 1000);
    }
}

From source file:com.nttec.everychan.ui.presentation.PresentationModel.java

/**
 * ?//  w  w  w .jav a 2  s . c  om
 * @param source ?? ? -  {@link SerializablePage}
 * @param localTime ?,   ???  ?  (? true),  ? ??  (? false)
 * @param reduceNames ? true,  ?   (. ?)   ??
 * @param spanClickListener  ?? URL  ?, ??   ?,   ??  e-mail (mailto)
 * @param imageGetter  , ???  ? ? (, ?)
 * @param theme ? 
 * @param floatingModels ??    ?  ?.  ? - ? 
 * ,  - ? ? ?     (gif, , ). 
 * ?  null, ?    .
 */
public PresentationModel(SerializablePage source, boolean localTime, boolean reduceNames,
        URLSpanClickListener spanClickListener, ImageGetter imageGetter, Theme theme,
        FloatingModel[] floatingModels) {
    if (source.pageModel.type == UrlPageModel.TYPE_OTHERPAGE)
        throw new IllegalArgumentException();
    this.source = source;
    this.spanClickListener = spanClickListener;
    this.imageGetter = imageGetter;
    this.theme = theme;
    this.floatingModels = floatingModels;
    this.reduceNames = reduceNames;
    Database database = MainApplication.getInstance().database;
    this.isHiddenDelegate = source.pageModel.type == UrlPageModel.TYPE_THREADPAGE
            ? database.getCachedIsHiddenDelegate(source.pageModel.chanName, source.pageModel.boardName,
                    source.pageModel.threadNumber)
            : database.getDefaultIsHiddenDelegate();
    this.autohideRules = new ArrayList<AutohideActivity.CompiledAutohideRule>();
    try {
        JSONArray autohideJson = new JSONArray(MainApplication.getInstance().settings.getAutohideRulesJson());
        for (int i = 0; i < autohideJson.length(); ++i) {
            AutohideActivity.AutohideRule rule = AutohideActivity.AutohideRule
                    .fromJson(autohideJson.getJSONObject(i));
            if (rule.matches(source.pageModel.chanName, source.pageModel.boardName,
                    source.pageModel.threadNumber)) {
                this.autohideRules.add(new AutohideActivity.CompiledAutohideRule(rule));
            }
        }
    } catch (Exception e) {
        Logger.e(TAG, "error while processing regex autohide rules", e);
    }
    AndroidDateFormat.initPattern();
    String datePattern = AndroidDateFormat.getPattern();
    DateFormat dateFormat = datePattern == null
            ? DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
            : new SimpleDateFormat(datePattern, Locale.US);
    dateFormat.setTimeZone(
            localTime ? TimeZone.getDefault() : TimeZone.getTimeZone(source.boardModel.timeZoneId));
    this.dateFormat = dateFormat;
    this.size = getSerializablePageSize(source);
}

From source file:net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.java

protected void setTimeZone() {
    String timeZoneIdParam = (String) getParameterValue(JRJdbcQueryExecuterFactory.PROPERTY_TIME_ZONE, true);
    String timeZoneIdProp = getPropertiesUtil().getProperty(dataset,
            JRJdbcQueryExecuterFactory.PROPERTY_TIME_ZONE);

    if (log.isDebugEnabled()) {
        log.debug("system timezone is " + TimeZone.getDefault());
        log.debug("report timezone is " + getParameterValue(JRParameter.REPORT_TIME_ZONE, true));
        log.debug("JDBC timezone parameter is " + timeZoneIdParam);
        log.debug("JDBC timezone property is " + timeZoneIdProp);
    }//from www  .  ja v  a2s .co m

    String parametersTimeZoneId = (String) getParameterValue(
            JRJdbcQueryExecuterFactory.PROPERTY_PARAMETERS_TIME_ZONE, true);
    if (log.isDebugEnabled()) {
        log.debug("JDBC parameters timezone parameter is " + parametersTimeZoneId);
    }
    parametersTimeZoneId = parametersTimeZoneId == null ? timeZoneIdParam : parametersTimeZoneId;
    if (parametersTimeZoneId != null) {
        parametersTimeZoneOverride = true;
    } else {
        parametersTimeZoneId = getPropertiesUtil().getProperty(dataset,
                JRJdbcQueryExecuterFactory.PROPERTY_PARAMETERS_TIME_ZONE);
        if (log.isDebugEnabled()) {
            log.debug("JDBC parameters timezone property is " + parametersTimeZoneId);
        }
        parametersTimeZoneId = parametersTimeZoneId == null ? timeZoneIdProp : parametersTimeZoneId;
    }
    parametersTimeZone = resolveTimeZone(parametersTimeZoneId);
    if (log.isDebugEnabled()) {
        log.debug("parameters timezone " + parametersTimeZone);
    }

    String fieldsTimeZoneId = (String) getParameterValue(JRJdbcQueryExecuterFactory.PROPERTY_FIELDS_TIME_ZONE,
            true);
    if (log.isDebugEnabled()) {
        log.debug("JDBC fields timezone parameter is " + fieldsTimeZoneId);
    }
    fieldsTimeZoneId = fieldsTimeZoneId == null ? timeZoneIdParam : fieldsTimeZoneId;
    if (fieldsTimeZoneId != null) {
        fieldsTimeZoneOverride = true;
    } else {
        fieldsTimeZoneId = getPropertiesUtil().getProperty(dataset,
                JRJdbcQueryExecuterFactory.PROPERTY_FIELDS_TIME_ZONE);
        if (log.isDebugEnabled()) {
            log.debug("JDBC fields timezone property is " + fieldsTimeZoneId);
        }
        fieldsTimeZoneId = fieldsTimeZoneId == null ? timeZoneIdProp : fieldsTimeZoneId;
    }
    fieldsTimeZone = resolveTimeZone(fieldsTimeZoneId);
    if (log.isDebugEnabled()) {
        log.debug("fields timezone " + fieldsTimeZone);
    }
}