Example usage for org.apache.http.client.utils URIBuilder setUserInfo

List of usage examples for org.apache.http.client.utils URIBuilder setUserInfo

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setUserInfo.

Prototype

public URIBuilder setUserInfo(final String username, final String password) 

Source Link

Document

Sets URI user info as a combination of username and password.

Usage

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

private String makeCredentialsPrefix(final String sitePrefix, final String name, final String password) {
    try {/*from w  w w  .j  a  v a2  s  . co  m*/
        final URIBuilder builder = new URIBuilder(sitePrefix);

        builder.setUserInfo(name, password);

        return builder.build().toString();
    } catch (final URISyntaxException e) {
        return sitePrefix;
    }
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") })
public String execute() throws Exception {
    int int1 = 401, int0 = 0;
    String string1 = null;/*from w  w  w.j  av a2  s .c  om*/
    URL url1 = null;
    URI uri1 = null;
    HttpGet httpGet1 = null;
    HttpResponse httpResponse1 = null;
    HttpEntity httpEntity1 = null;
    HttpPost httpPost1 = null;
    HttpHost httpHost1 = null;
    DefaultHttpClient httpClient1 = null;
    File file1 = null;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    BeanComparator beanComparator1 = null;
    List<Map<String, Object>> list1 = null, list2 = null;
    Map<String, Object> map1 = null;
    Object object1 = null;
    int toIndex = rows * page;
    int fromIndex = toIndex - rows;
    GridModel1 jsonObject1 = null;
    Gson gson = null;
    Long long1 = -1L;
    java.util.Date date1 = null;
    URIBuilder uriBuilder1 = null;
    Node node1 = null;
    Element element1 = null;
    NodeList nodeList1 = null;
    Document document1 = null;
    DocumentBuilder documentBuilder1 = null;
    DocumentBuilderFactory documentBuilderFactory1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;

    try {
        if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) {
            sid = new String(Base64.decodeBase64(sid.getBytes()));
            uid = new String(Base64.decodeBase64(uid.getBytes()));
            pid = new String(Base64.decodeBase64(pid.getBytes()));
            httpClient1 = new DefaultHttpClient();
            url1 = new URL(sid);
            uriBuilder1 = new URIBuilder(sid);
            uriBuilder1.setParameter("j_username", uid);
            uriBuilder1.setParameter("j_password", pid);
            uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString);
            uriBuilder1.setUserInfo(uid, pid);
            uri1 = uriBuilder1.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int1 = httpResponse1.getStatusLine().getStatusCode();
            if (int1 == HttpStatus.SC_OK) {
                httpEntity1 = httpResponse1.getEntity();
                inputStream1 = httpResponse1.getEntity().getContent();
                if (inputStream1 != null) {
                    documentBuilderFactory1 = DocumentBuilderFactory.newInstance();
                    documentBuilder1 = documentBuilderFactory1.newDocumentBuilder();
                    document1 = documentBuilder1.parse(inputStream1);
                    document1.getDocumentElement().normalize();
                    nodeList1 = document1.getElementsByTagName("resourceDescriptor");
                    int1 = nodeList1.getLength();
                    list1 = new ArrayList<Map<String, Object>>();
                    for (int0 = 0; int0 < int1; int0++) {
                        node1 = nodeList1.item(int0);
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            element1 = (Element) node1;
                            map1 = new HashMap<String, Object>();
                            map1.put("wsType", element1.getAttribute("wsType"));
                            map1.put("uriString", element1.getAttribute("uriString"));
                            string1 = getTagValue("label", element1);
                            map1.put("label1", StringUtils.defaultString(string1));
                            string1 = getTagValue("description", element1);
                            map1.put("description", StringUtils.defaultString(string1));
                            string1 = getTagValue("creationDate", element1);
                            long1 = (string1 == null) ? -1L
                                    : NumberUtils.toLong(StringUtils.trim(string1), -1L);
                            if (long1 > 0) {
                                if (StringUtils.isNotBlank(timeZone1)) {
                                    dateTime1 = new org.joda.time.DateTime(long1);
                                    dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1));
                                    date1 = dateTime2.toLocalDateTime().toDate();
                                } else {
                                    date1 = new java.util.Date(long1);
                                }
                            } else {
                                date1 = null;
                            }
                            map1.put("creationDate", date1);
                            map1.put("type1", getText(element1.getAttribute("wsType")));
                            list1.add(map1);
                        }
                    }
                }
                EntityUtils.consume(httpEntity1);
            }
        }
    } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException
            | SAXException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException
            | java.net.MalformedURLException | java.net.UnknownHostException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (IOException exception1) {
        httpGet1.abort();
        exception1.printStackTrace();
        return ERROR;
    } finally {
        if (httpClient1 != null)
            httpClient1.getConnectionManager().shutdown();
        if (list1 != null) {
            records = list1.size();
            if (list1.size() > 0) {
                if (StringUtils.isNotEmpty(sidx)) {
                    if (StringUtils.equals(sord, "desc")) {
                        beanComparator1 = new BeanComparator(sidx,
                                new ReverseComparator(new ComparableComparator()));
                    } else {
                        beanComparator1 = new BeanComparator(sidx);
                    }
                    Collections.sort(list1, beanComparator1);
                }
                if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) {
                    Iterator iterator1 = list1.iterator();
                    while (iterator1.hasNext()) {
                        map1 = (Map<String, Object>) iterator1.next();
                        for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
                            if (StringUtils.equals(entry1.getKey(), searchField)) {
                                object1 = entry1.getValue();
                                if (searchFilter(searchField, searchOper, searchString, object1))
                                    iterator1.remove();
                                break;
                            }
                        }
                    }
                    records = list1.size();
                }
                if (toIndex > records)
                    toIndex = records;
                if (fromIndex > toIndex) {
                    fromIndex = toIndex - rows;
                    if (fromIndex < 0)
                        fromIndex = 0;
                }
                if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex)
                    list2 = list1.subList(fromIndex, toIndex);

            }
            total = (int) Math.ceil((double) records / (double) rows);
            if (page > total)
                page = total;
            jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total,
                    records, id, list2);
            gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
            jsonData = gson.toJson(jsonObject1);
        }
        IOUtils.closeQuietly(inputStream1);
    }
    return SUCCESS;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

public ProbeCalendarRemoteUrlResult probeCalendarRemoteUrl(Calendar.Provider provider, URI url, String username,
        String password) throws WTException {
    if (!Calendar.isProviderRemote(provider)) {
        throw new WTException("Provider is not remote (webcal or CalDAV) [{}]",
                EnumUtils.toSerializedName(provider));
    }/*from   w ww  . j  a v a2  s  .co  m*/

    try {
        if (Calendar.Provider.WEBCAL.equals(provider)) {
            URIBuilder builder = new URIBuilder(url);
            if (StringUtils.equalsIgnoreCase(builder.getScheme(), "webcal")) {
                builder.setScheme("http"); // Force http scheme
            }
            if (!StringUtils.isBlank(username) && !StringUtils.isBlank(username)) {
                builder.setUserInfo(username, password);
            }
            URI newUrl = URIUtils.buildQuietly(builder);

            HttpClient httpCli = null;
            try {
                logger.debug("Checking remote calendar URL [{}]", newUrl.toString());
                httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(),
                        newUrl);
                return HttpClientUtils.exists(httpCli, newUrl)
                        ? new ProbeCalendarRemoteUrlResult(FilenameUtils.getBaseName(newUrl.getPath()))
                        : null;
            } finally {
                HttpClientUtils.closeQuietly(httpCli);
            }

        } else if (Calendar.Provider.CALDAV.equals(provider)) {
            CalDav dav = getCalDav(username, password);

            try {
                DavCalendar dcal = dav.getCalendar(url.toString());
                return (dcal != null) ? new ProbeCalendarRemoteUrlResult(dcal.getDisplayName()) : null;

            } catch (DavException ex) {
                logger.error("DAV error", ex);
                return null;
            }
        } else {
            throw new WTException("Unsupported provider");
        }

    } catch (IOException ex) {
        throw new WTException(ex, "Unable to check URL [{0}]", url.toString());
    }
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

public void syncRemoteCalendar(int calendarId, boolean full) throws WTException {
    final UserProfile.Data udata = WT.getUserData(getTargetProfileId());
    final ICalendarInput icalInput = new ICalendarInput(udata.getTimeZone());
    final String PENDING_KEY = String.valueOf(calendarId);
    CalendarDAO calDao = CalendarDAO.getInstance();
    Connection con = null;/*from www  .j a va2s  . com*/

    if (pendingRemoteCalendarSyncs.putIfAbsent(PENDING_KEY, RunContext.getRunProfileId()) != null) {
        throw new ConcurrentSyncException("Sync activity is already running [{}, {}]", calendarId,
                RunContext.getRunProfileId());
    }

    try {
        //checkRightsOnCalendarFolder(calendarId, "READ");

        con = WT.getConnection(SERVICE_ID, false);
        Calendar cal = ManagerUtils.createCalendar(calDao.selectById(con, calendarId));
        if (cal == null)
            throw new WTException("Calendar not found [{0}]", calendarId);
        if (!Calendar.Provider.WEBCAL.equals(cal.getProvider())
                && !Calendar.Provider.CALDAV.equals(cal.getProvider())) {
            throw new WTException("Specified calendar is not remote (webcal or CalDAV) [{0}]", calendarId);
        }

        // Force a full update if last-sync date is null
        if (cal.getRemoteSyncTimestamp() == null)
            full = true;

        CalendarRemoteParameters params = LangUtils.deserialize(cal.getParameters(),
                CalendarRemoteParameters.class);
        if (params == null)
            throw new WTException("Unable to deserialize remote parameters");
        if (params.url == null)
            throw new WTException("Remote URL is undefined");

        if (Calendar.Provider.WEBCAL.equals(cal.getProvider())) {
            final String PREFIX = "webcal-";
            File tempFile = null;

            URIBuilder builder = new URIBuilder(params.url);
            if (StringUtils.equalsIgnoreCase(builder.getScheme(), "webcal")) {
                builder.setScheme("http"); // Force http scheme
            }
            if (!StringUtils.isBlank(params.username) && !StringUtils.isBlank(params.username)) {
                builder.setUserInfo(params.username, params.password);
            }
            URI newUrl = URIUtils.buildQuietly(builder);

            try {
                final DateTime newLastSync = DateTimeUtils.now();
                tempFile = WT.createTempFile(PREFIX, null);

                // Retrieve webcal content (iCalendar) from the specified URL 
                // and save it locally
                logger.debug("Downloading iCalendar file from URL [{}]", newUrl);
                HttpClient httpCli = null;
                FileOutputStream os = null;
                try {
                    httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(),
                            newUrl);
                    os = new FileOutputStream(tempFile);
                    HttpClientUtils.writeContent(httpCli, newUrl, os);

                } catch (IOException ex) {
                    throw new WTException(ex, "Unable to retrieve webcal [{0}]", newUrl);
                } finally {
                    IOUtils.closeQuietly(os);
                    HttpClientUtils.closeQuietly(httpCli);
                }
                logger.debug("Saved to temp file [{}]", tempFile.getName());

                // Parse downloaded iCalendar
                logger.debug("Parsing downloaded iCalendar file");
                net.fortuna.ical4j.model.Calendar ical = null;
                FileInputStream is = null;
                try {
                    is = new FileInputStream(tempFile);
                    ICalendarUtils.relaxParsingAndCompatibility();
                    ical = ICalendarUtils.parse(is);
                    //TODO: add support to FILENAME property (Google https://github.com/ical4j/ical4j/issues/69)
                } catch (IOException | ParserException ex) {
                    throw new WTException(ex, "Unable to read webcal");
                } finally {
                    IOUtils.closeQuietly(os);
                }

                icalInput.withIncludeVEventSourceInOutput(true);
                ArrayList<EventInput> input = icalInput.fromICalendarFile(ical, null);
                logger.debug("Found {} events", input.size());

                Map<String, VEventHrefSync> syncByHref = null;

                if (full) {
                    logger.debug("Cleaning up calendar [{}]", calendarId);
                    doEventsDeleteByCalendar(con, calendarId, false);
                } else {
                    EventDAO evtDao = EventDAO.getInstance();
                    syncByHref = evtDao.viewHrefSyncDataByCalendar(con, calendarId);
                }

                // Inserts/Updates data...
                logger.debug("Inserting/Updating events...");
                try {
                    String autoUidPrefix = DigestUtils.md5Hex(newUrl.toString()); // auto-gen base prefix in case of missing UID
                    HashSet<String> hrefs = new HashSet<>();
                    HashMap<String, OEvent> cache = new HashMap<>();
                    int i = 0;
                    for (EventInput ei : input) {
                        if (StringUtils.isBlank(ei.event.getPublicUid())) {
                            String autoUid = autoUidPrefix + "-" + i;
                            ei.event.setPublicUid(autoUid);
                            logger.trace("Missing UID: using auto-gen value. [{}]", autoUid);
                        }
                        String href = ManagerUtils.buildHref(ei.event.getPublicUid());

                        //if (logger.isTraceEnabled()) logger.trace("{}", ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                        if (hrefs.contains(href)) {
                            logger.trace("Event duplicated. Skipped! [{}]", href);
                            continue;
                        }

                        boolean skip = false;
                        Integer matchingEventId = null;
                        String eiHash = DigestUtils.md5Hex(ei.sourceEvent.toString());

                        if (syncByHref != null) { // Only if... (!full) see above!
                            VEventHrefSync hrefSync = syncByHref.remove(href);
                            if (hrefSync != null) { // Href found -> maybe updated item
                                if (!StringUtils.equals(hrefSync.getEtag(), eiHash)) {
                                    matchingEventId = hrefSync.getEventId();
                                    logger.trace("Event updated [{}, {}]", href, eiHash);
                                } else {
                                    skip = true;
                                    logger.trace("Event not modified [{}, {}]", href, eiHash);
                                }
                            } else { // Href not found -> added item
                                logger.trace("Event newly added [{}, {}]", href, eiHash);
                            }
                        }

                        if (!skip) {
                            ei.event.setCalendarId(calendarId);
                            ei.event.setHref(href);
                            ei.event.setEtag(eiHash);

                            if (matchingEventId != null) {
                                ei.event.setEventId(matchingEventId);
                                boolean updated = doEventInputUpdate(con, cache, ei);
                                if (!updated)
                                    throw new WTException("Event not found [{}]", ei.event.getEventId());

                            } else {
                                doEventInputInsert(con, cache, ei);
                            }
                        }

                        hrefs.add(href); // Marks as processed!
                    }

                    if (syncByHref != null) { // Only if... (!full) see above!
                        // Remaining hrefs -> deleted items
                        for (VEventHrefSync hrefSync : syncByHref.values()) {
                            logger.trace("Event deleted [{}]", hrefSync.getHref());
                            doEventDelete(con, hrefSync.getEventId(), false);
                        }
                    }

                    cache.clear();
                    calDao.updateRemoteSyncById(con, calendarId, newLastSync, null);
                    DbUtils.commitQuietly(con);

                } catch (Exception ex) {
                    DbUtils.rollbackQuietly(con);
                    throw new WTException(ex, "Error importing iCalendar");
                }

            } finally {
                if (tempFile != null) {
                    logger.debug("Removing temp file [{}]", tempFile.getName());
                    WT.deleteTempFile(tempFile);
                }
            }

        } else if (Calendar.Provider.CALDAV.equals(cal.getProvider())) {
            CalDav dav = getCalDav(params.username, params.password);

            try {
                DavCalendar dcal = dav.getCalendarSyncToken(params.url.toString());
                if (dcal == null)
                    throw new WTException("DAV calendar not found");

                final boolean syncIsSupported = !StringUtils.isBlank(dcal.getSyncToken());
                final DateTime newLastSync = DateTimeUtils.now();

                if (!full && (syncIsSupported && !StringUtils.isBlank(cal.getRemoteSyncTag()))) { // Partial update using SYNC mode
                    String newSyncToken = dcal.getSyncToken();

                    logger.debug("Querying CalDAV endpoint for changes [{}, {}]", params.url.toString(),
                            cal.getRemoteSyncTag());
                    List<DavSyncStatus> changes = dav.getCalendarChanges(params.url.toString(),
                            cal.getRemoteSyncTag());
                    logger.debug("Returned {} items", changes.size());

                    try {
                        if (!changes.isEmpty()) {
                            EventDAO evtDao = EventDAO.getInstance();
                            Map<String, List<Integer>> eventIdsByHref = evtDao.selectHrefsByByCalendar(con,
                                    calendarId);

                            // Process changes...
                            logger.debug("Processing changes...");
                            HashSet<String> hrefs = new HashSet<>();
                            for (DavSyncStatus change : changes) {
                                String href = FilenameUtils.getName(change.getPath());
                                //String href = change.getPath();

                                if (DavUtil.HTTP_SC_TEXT_OK.equals(change.getResponseStatus())) {
                                    hrefs.add(href);

                                } else { // Event deleted
                                    List<Integer> eventIds = eventIdsByHref.get(href);
                                    Integer eventId = (eventIds != null) ? eventIds.get(eventIds.size() - 1)
                                            : null;
                                    if (eventId == null) {
                                        logger.warn("Deletion not possible. Event path not found [{}]",
                                                PathUtils.concatPaths(dcal.getPath(),
                                                        FilenameUtils.getName(href)));
                                        continue;
                                    }
                                    doEventDelete(con, eventId, false);
                                }
                            }

                            // Retrieves events list from DAV endpoint (using multiget)
                            logger.debug("Retrieving inserted/updated events [{}]", hrefs.size());
                            Collection<String> paths = hrefs.stream().map(
                                    href -> PathUtils.concatPaths(dcal.getPath(), FilenameUtils.getName(href)))
                                    .collect(Collectors.toList());
                            List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString(), paths);
                            //List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString(), hrefs);

                            // Inserts/Updates data...
                            logger.debug("Inserting/Updating events...");
                            HashMap<String, OEvent> cache = new HashMap<>();
                            for (DavCalendarEvent devt : devts) {
                                String href = FilenameUtils.getName(devt.getPath());
                                //String href = devt.getPath();

                                if (logger.isTraceEnabled())
                                    logger.trace("{}",
                                            ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                                List<Integer> eventIds = eventIdsByHref.get(href);
                                Integer eventId = (eventIds != null) ? eventIds.get(eventIds.size() - 1) : null;

                                final ArrayList<EventInput> input = icalInput
                                        .fromICalendarFile(devt.getCalendar(), null);
                                if (input.size() != 1)
                                    throw new WTException("iCal must contain one event");
                                final EventInput ei = input.get(0);

                                if (eventId != null) {
                                    doEventDelete(con, eventId, false);
                                }

                                ei.event.setCalendarId(calendarId);
                                ei.event.setHref(href);
                                ei.event.setEtag(devt.geteTag());
                                doEventInputInsert(con, cache, ei);
                            }
                        }

                        calDao.updateRemoteSyncById(con, calendarId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing iCalendar");
                    }

                } else { // Full update or partial computing hashes
                    String newSyncToken = null;
                    if (syncIsSupported) { // If supported, saves last sync-token issued by the server
                        newSyncToken = dcal.getSyncToken();
                    }

                    // Retrieves cards from DAV endpoint
                    logger.debug("Querying CalDAV endpoint [{}]", params.url.toString());
                    List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString());
                    logger.debug("Returned {} items", devts.size());

                    // Handles data...
                    try {
                        Map<String, VEventHrefSync> syncByHref = null;

                        if (full) {
                            logger.debug("Cleaning up calendar [{}]", calendarId);
                            doEventsDeleteByCalendar(con, calendarId, false);
                        } else if (!full && !syncIsSupported) {
                            // This hash-map is only needed when syncing using hashes
                            EventDAO evtDao = EventDAO.getInstance();
                            syncByHref = evtDao.viewHrefSyncDataByCalendar(con, calendarId);
                        }

                        logger.debug("Processing results...");
                        // Define a simple map in order to check duplicates.
                        // eg. SOGo passes same card twice :(
                        HashSet<String> hrefs = new HashSet<>();
                        HashMap<String, OEvent> cache = new HashMap<>();
                        for (DavCalendarEvent devt : devts) {
                            String href = PathUtils.getFileName(devt.getPath());
                            //String href = devt.getPath();
                            String etag = devt.geteTag();

                            if (logger.isTraceEnabled())
                                logger.trace("{}",
                                        ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                            if (hrefs.contains(href)) {
                                logger.trace("Card duplicated. Skipped! [{}]", href);
                                continue;
                            }

                            boolean skip = false;
                            Integer matchingEventId = null;

                            if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                                //String prodId = ICalendarUtils.buildProdId(ManagerUtils.getProductName());
                                //String hash = DigestUtils.md5Hex(new ICalendarOutput(prodId, true).write(devt.getCalendar()));
                                String hash = DigestUtils
                                        .md5Hex(ICalendarUtils.getVEvent(devt.getCalendar()).toString());

                                VEventHrefSync hrefSync = syncByHref.remove(href);
                                if (hrefSync != null) { // Href found -> maybe updated item
                                    if (!StringUtils.equals(hrefSync.getEtag(), hash)) {
                                        matchingEventId = hrefSync.getEventId();
                                        etag = hash;
                                        logger.trace("Event updated [{}, {}]", href, hash);
                                    } else {
                                        skip = true;
                                        logger.trace("Event not modified [{}, {}]", href, hash);
                                    }
                                } else { // Href not found -> added item
                                    logger.trace("Event newly added [{}]", href);
                                    etag = hash;
                                }
                            }

                            if (!skip) {
                                final ArrayList<EventInput> input = icalInput
                                        .fromICalendarFile(devt.getCalendar(), null);
                                if (input.size() != 1)
                                    throw new WTException("iCal must contain one event");
                                final EventInput ei = input.get(0);
                                ei.event.setCalendarId(calendarId);
                                ei.event.setHref(href);
                                ei.event.setEtag(etag);

                                if (matchingEventId == null) {
                                    doEventInputInsert(con, cache, ei);
                                } else {
                                    ei.event.setEventId(matchingEventId);
                                    boolean updated = doEventInputUpdate(con, cache, ei);
                                    if (!updated)
                                        throw new WTException("Event not found [{}]", ei.event.getEventId());
                                }
                            }

                            hrefs.add(href); // Marks as processed!
                        }

                        if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                            // Remaining hrefs -> deleted items
                            for (VEventHrefSync hrefSync : syncByHref.values()) {
                                logger.trace("Event deleted [{}]", hrefSync.getHref());
                                doEventDelete(con, hrefSync.getEventId(), false);
                            }
                        }

                        calDao.updateRemoteSyncById(con, calendarId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing iCalendar");
                    }
                }

            } catch (DavException ex) {
                throw new WTException(ex, "CalDAV error");
            }
        }

    } catch (SQLException | DAOException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
        pendingRemoteCalendarSyncs.remove(PENDING_KEY);
    }
}

From source file:ching.icecreaming.action.ViewAction.java

@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"),
        @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    Enumeration enumerator = null;
    String[] array1 = null, array2 = null;
    int int1 = -1, int2 = -1, int3 = -1;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    java.io.File file1 = null, file2 = null, dir1 = null;
    List<File> files = null;
    HttpHost httpHost1 = null;//from www.  j a v  a 2s. c  o m
    HttpGet httpGet1 = null, httpGet2 = null;
    HttpPut httpPut1 = null;
    URI uri1 = null;
    URL url1 = null;
    DefaultHttpClient httpClient1 = null;
    URIBuilder uriBuilder1 = null, uriBuilder2 = null;
    HttpResponse httpResponse1 = null, httpResponse2 = null;
    HttpEntity httpEntity1 = null, httpEntity2 = null;
    List<NameValuePair> nameValuePair1 = null;
    String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN;
    XMLConfiguration xmlConfiguration = null;
    List<HierarchicalConfiguration> list1 = null, list2 = null;
    HierarchicalConfiguration hierarchicalConfiguration2 = null;
    DataModel1 dataModel1 = null;
    DataModel2 dataModel2 = null;
    List<DataModel1> listObject1 = null, listObject3 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    org.joda.time.Period period1 = null;
    PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears()
            .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years")))
            .appendSeparator(" ").appendMonths()
            .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months")))
            .appendSeparator(" ").appendWeeks()
            .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks")))
            .appendSeparator(" ").appendDays()
            .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days")))
            .appendSeparator(" ").appendHours()
            .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours")))
            .appendSeparator(" ").appendMinutes()
            .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes")))
            .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2)
            .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds")))
            .printZeroNever().toFormatter();
    if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
        urlString = portletPreferences.getValue("urlString", "/");
        wsType = portletPreferences.getValue("wsType", "folder");
    }
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties");
    timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    enumerator = portletPreferences.getNames();
    if (enumerator.hasMoreElements()) {
        array1 = portletPreferences.getValues("server", null);
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
            return1 = INPUT;
        } else {
            return1 = LOGIN;
        }
    } else {
        return1 = LOGIN;
    }

    if (StringUtils.equals(urlString, "/")) {

        if (listObject1 != null) {
            listObject1.clear();
        }
        if (session.containsKey("breadcrumbs")) {
            session.remove("breadcrumbs");
        }
    } else {
        array2 = StringUtils.split(urlString, "/");
        listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs")
                : new ArrayList<DataModel1>();
        int2 = array2.length - listObject1.size();
        if (int2 > 0) {
            listObject1.add(new DataModel1(urlString, label1));
        } else {
            int2 += listObject1.size();
            for (int1 = listObject1.size() - 1; int1 >= int2; int1--) {
                listObject1.remove(int1);
            }
        }
        session.put("breadcrumbs", listObject1);
    }
    switch (wsType) {
    case "folder":
        break;
    case "reportUnit":
        try {
            dateTime1 = new org.joda.time.DateTime();
            return1 = INPUT;
            httpClient1 = new DefaultHttpClient();
            if (StringUtils.equals(button1, getText("Print"))) {
                nameValuePair1 = new ArrayList<NameValuePair>();
                if (listObject2 != null) {
                    if (listObject2.size() > 0) {
                        for (DataModel2 dataObject2 : listObject2) {
                            listObject3 = dataObject2.getOptions();
                            if (listObject3 == null) {
                                string2 = dataObject2.getValue1();
                                if (StringUtils.isNotBlank(string2))
                                    nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2));
                            } else {
                                for (int1 = listObject3.size() - 1; int1 >= 0; int1--) {
                                    dataModel1 = (DataModel1) listObject3.get(int1);
                                    string2 = dataModel1.getString2();
                                    if (StringUtils.isNotBlank(string2))
                                        nameValuePair1
                                                .add(new BasicNameValuePair(dataObject2.getId(), string2));
                                }
                            }
                        }
                    }
                }
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                if (StringUtils.isBlank(format1))
                    format1 = "pdf";
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1);
                if (StringUtils.isNotBlank(locale2)) {
                    nameValuePair1.add(new BasicNameValuePair("userLocale", locale2));
                }
                if (StringUtils.isNotBlank(page1)) {
                    if (NumberUtils.isNumber(page1)) {
                        nameValuePair1.add(new BasicNameValuePair("page", page1));
                    }
                }
                if (nameValuePair1.size() > 0) {
                    uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8"));
                }
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                if (int1 == HttpStatus.SC_OK) {
                    string3 = System.getProperty("java.io.tmpdir") + File.separator
                            + httpServletRequest.getSession().getId();
                    dir1 = new File(string3);
                    if (!dir1.exists()) {
                        dir1.mkdir();
                    }
                    httpEntity1 = httpResponse1.getEntity();
                    file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1);
                    if (StringUtils.equalsIgnoreCase(format1, "html")) {
                        result1 = EntityUtils.toString(httpEntity1);
                        FileUtils.writeStringToFile(file1, result1);
                        array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\"");
                        if (ArrayUtils.isNotEmpty(array1)) {
                            dir1 = new File(
                                    string3 + File.separator + FilenameUtils.getBaseName(file1.getName()));
                            if (dir1.exists()) {
                                FileUtils.deleteDirectory(dir1);
                            }
                            file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            if (file2.exists()) {
                                if (FileUtils.deleteQuietly(file2)) {
                                }
                            }
                            for (int2 = 0; int2 < array1.length; int2++) {
                                try {
                                    string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/"
                                            + StringUtils.substringAfter(array1[int2], "/");
                                    uriBuilder1.setPath(string2);
                                    uri1 = uriBuilder1.build();
                                    httpGet1 = new HttpGet(uri1);
                                    httpResponse1 = httpClient1.execute(httpGet1);
                                    int1 = httpResponse1.getStatusLine().getStatusCode();
                                } finally {
                                    if (int1 == HttpStatus.SC_OK) {
                                        try {
                                            string2 = StringUtils.substringBeforeLast(array1[int2], "/");
                                            dir1 = new File(string3 + File.separator + string2);
                                            if (!dir1.exists()) {
                                                dir1.mkdirs();
                                            }
                                            httpEntity1 = httpResponse1.getEntity();
                                            inputStream1 = httpEntity1.getContent();
                                        } finally {
                                            string1 = StringUtils.substringAfterLast(array1[int2], "/");
                                            file2 = new File(string3 + File.separator + string2, string1);
                                            outputStream1 = new FileOutputStream(file2);
                                            IOUtils.copy(inputStream1, outputStream1);
                                        }
                                    }
                                }
                            }
                            outputStream1 = new FileOutputStream(
                                    FilenameUtils.getFullPath(file1.getAbsolutePath())
                                            + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory()
                                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1);
                            archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName()));
                            IOUtils.copy(new FileInputStream(file1), archiveOutputStream1);
                            archiveOutputStream1.closeArchiveEntry();
                            dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()));
                            files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE,
                                    TrueFileFilter.INSTANCE);
                            for (File file3 : files) {
                                archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils
                                        .substringAfter(file3.getCanonicalPath(), string3 + File.separator)));
                                IOUtils.copy(new FileInputStream(file3), archiveOutputStream1);
                                archiveOutputStream1.closeArchiveEntry();
                            }
                            archiveOutputStream1.close();
                        }
                        bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false);
                        string4 = bugfixGateIn
                                ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=",
                                        portletRequest.getContextPath(),
                                        httpServletRequest.getSession().getId())
                                : String.format("<img src=\"%s/namespace1/file-link?fileName=",
                                        portletRequest.getContextPath());
                        result1 = StringUtils.replace(result1, "<img src=\"", string4);
                    } else {
                        inputStream1 = httpEntity1.getContent();
                        outputStream1 = new FileOutputStream(file1);
                        IOUtils.copy(inputStream1, outputStream1);
                        result1 = file1.getAbsolutePath();
                    }
                    return1 = SUCCESS;
                } else {
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                }
                dateTime2 = new org.joda.time.DateTime();
                period1 = new Period(dateTime1, dateTime2.plusSeconds(1));
                message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1);
            } else {
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls");
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                switch (int1) {
                case HttpStatus.SC_NO_CONTENT:
                    break;
                case HttpStatus.SC_OK:
                    httpEntity1 = httpResponse1.getEntity();
                    if (httpEntity1 != null) {
                        inputStream1 = httpEntity1.getContent();
                        if (inputStream1 != null) {
                            xmlConfiguration = new XMLConfiguration();
                            xmlConfiguration.load(inputStream1);
                            list1 = xmlConfiguration.configurationsAt("inputControl");
                            if (list1.size() > 0) {
                                listObject2 = new ArrayList<DataModel2>();
                                for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) {
                                    string2 = hierarchicalConfiguration1.getString("type");
                                    dataModel2 = new DataModel2();
                                    dataModel2.setId(hierarchicalConfiguration1.getString("id"));
                                    dataModel2.setLabel1(hierarchicalConfiguration1.getString("label"));
                                    dataModel2.setType1(string2);
                                    dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory"));
                                    dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly"));
                                    dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible"));
                                    switch (string2) {
                                    case "bool":
                                    case "singleValueText":
                                    case "singleValueNumber":
                                    case "singleValueDate":
                                    case "singleValueDatetime":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        dataModel2.setValue1(hierarchicalConfiguration2.getString("value"));
                                        break;
                                    case "singleSelect":
                                    case "singleSelectRadio":
                                    case "multiSelect":
                                    case "multiSelectCheckbox":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        list2 = hierarchicalConfiguration2.configurationsAt("options.option");
                                        if (list2.size() > 0) {
                                            listObject3 = new ArrayList<DataModel1>();
                                            for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) {
                                                dataModel1 = new DataModel1(
                                                        hierarchicalConfiguration3.getString("label"),
                                                        hierarchicalConfiguration3.getString("value"));
                                                if (hierarchicalConfiguration3.getBoolean("selected")) {
                                                    dataModel2.setValue1(
                                                            hierarchicalConfiguration3.getString("value"));
                                                }
                                                listObject3.add(dataModel1);
                                            }
                                            dataModel2.setOptions(listObject3);
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                    listObject2.add(dataModel2);
                                }
                            }
                        }
                    }
                    break;
                default:
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                    break;
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
                uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString);
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int2 = httpResponse1.getStatusLine().getStatusCode();
                if (int2 == HttpStatus.SC_OK) {
                    httpEntity1 = httpResponse1.getEntity();
                    inputStream1 = httpEntity1.getContent();
                    xmlConfiguration = new XMLConfiguration();
                    xmlConfiguration.load(inputStream1);
                    list1 = xmlConfiguration.configurationsAt("resourceDescriptor");
                    for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) {
                        if (StringUtils.equalsIgnoreCase(
                                StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) {
                            if (map1 == null)
                                map1 = new HashMap<String, String>();
                            string2 = StringUtils.substringBetween(
                                    StringUtils.substringAfter(
                                            hierarchicalConfiguration4.getString("[@uriString]"), "_files/"),
                                    "_", ".properties");
                            map1.put(string2,
                                    StringUtils.isBlank(string2) ? getText("Default") : getText(string2));
                        }
                    }
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
            }
        } catch (IOException | ConfigurationException | URISyntaxException exception1) {
            exception1.printStackTrace();
            addActionError(exception1.getLocalizedMessage());
            httpGet1.abort();
            return ERROR;
        } finally {
            httpClient1.getConnectionManager().shutdown();
            IOUtils.closeQuietly(inputStream1);
        }
        break;
    default:
        addActionError(getText("This.file.type.is.not.supported"));
        break;
    }
    if (return1 != LOGIN) {
        sid = new String(Base64.encodeBase64(sid.getBytes()));
        uid = new String(Base64.encodeBase64(uid.getBytes()));
        pid = new String(Base64.encodeBase64(pid.getBytes()));
    }
    return return1;
}