Example usage for java.net URISyntaxException printStackTrace

List of usage examples for java.net URISyntaxException printStackTrace

Introduction

In this page you can find the example usage for java.net URISyntaxException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:de.geeksfactory.opacclient.apis.Bibliotheca.java

protected DetailledItem parse_result(String html) {
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url);//from w  ww. j  a v a  2  s. co  m

    DetailledItem result = new DetailledItem();

    if (doc.select(".detail_cover img").size() == 1) {
        result.setCover(doc.select(".detail_cover img").get(0).attr("src"));
    }

    result.setTitle(doc.select(".detail_titel").text());

    Elements detailtrs = doc.select(".detailzeile table tr");
    for (int i = 0; i < detailtrs.size(); i++) {
        Element tr = detailtrs.get(i);
        if (tr.child(0).hasClass("detail_feld")) {
            String title = tr.child(0).text();
            String content = tr.child(1).text();
            if (title.equals("Gesamtwerk:") || title.equals("Erschienen in:")) {
                try {
                    if (tr.child(1).select("a").size() > 0) {
                        Element link = tr.child(1).select("a").first();
                        List<NameValuePair> query = URLEncodedUtils.parse(new URI(link.absUrl("href")),
                                "UTF-8");
                        for (NameValuePair q : query) {
                            if (q.getName().equals("MedienNr")) {
                                result.setCollectionId(q.getValue());
                            }
                        }
                    }
                } catch (URISyntaxException e) {
                }
            } else {

                if (content.contains("hier klicken") && tr.child(1).select("a").size() > 0) {
                    content += " " + tr.child(1).select("a").first().attr("href");
                }

                result.addDetail(new Detail(title, content));
            }
        }
    }

    Elements detailcenterlinks = doc.select(".detailzeile_center a.detail_link");
    for (int i = 0; i < detailcenterlinks.size(); i++) {
        Element a = detailcenterlinks.get(i);
        result.addDetail(new Detail(a.text().trim(), a.absUrl("href")));
    }

    try {
        JSONObject copymap = new JSONObject();
        if (data.has("copiestable")) {
            copymap = data.getJSONObject("copiestable");
        } else {
            Elements ths = doc.select(".exemplartab .exemplarmenubar th");
            for (int i = 0; i < ths.size(); i++) {
                Element th = ths.get(i);
                String head = th.text().trim();
                if (head.equals("Zweigstelle")) {
                    copymap.put("branch", i);
                } else if (head.equals("Abteilung")) {
                    copymap.put("department", i);
                } else if (head.equals("Bereich") || head.equals("Standort")) {
                    copymap.put("location", i);
                } else if (head.equals("Signatur")) {
                    copymap.put("signature", i);
                } else if (head.equals("Barcode") || head.equals("Medien-Nummer")) {
                    copymap.put("barcode", i);
                } else if (head.equals("Status")) {
                    copymap.put("status", i);
                } else if (head.equals("Frist") || head.matches("Verf.+gbar")) {
                    copymap.put("returndate", i);
                } else if (head.equals("Vorbestellungen") || head.equals("Reservierungen")) {
                    copymap.put("reservations", i);
                }
            }
        }
        Elements exemplartrs = doc.select(".exemplartab .tabExemplar, .exemplartab .tabExemplar_");
        DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
        for (int i = 0; i < exemplartrs.size(); i++) {
            Element tr = exemplartrs.get(i);

            Copy copy = new Copy();

            Iterator<?> keys = copymap.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                int index;
                try {
                    index = copymap.has(key) ? copymap.getInt(key) : -1;
                } catch (JSONException e1) {
                    index = -1;
                }
                if (index >= 0) {
                    try {
                        copy.set(key, tr.child(index).text(), fmt);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    }
                }
            }

            result.addCopy(copy);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Elements bandtrs = doc.select("table .tabBand a");
        for (int i = 0; i < bandtrs.size(); i++) {
            Element tr = bandtrs.get(i);

            Volume volume = new Volume();
            volume.setId(tr.attr("href").split("=")[1]);
            volume.setTitle(tr.text());
            result.addVolume(volume);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (doc.select(".detail_vorbest a").size() == 1) {
        result.setReservable(true);
        result.setReservation_info(doc.select(".detail_vorbest a").attr("href"));
    }
    return result;
}

From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImpl.java

@Override
public void addAuthToHttpRequest(HttpRequestBase httpRequestBase, Map<Object, Object> context) {

    String uri = httpRequestBase.getURI().toString();

    String instance = null;//from w ww .j a v a 2s .  c om
    String envelope = null;
    String requestURLHost = null;
    Integer fileId = null;
    String authentication = null;
    String sessionId = null;

    if (uri == null) {
        return;
    }

    // load bf context attributes
    if (context.get("instance") != null) {
        instance = (String) context.get("instance");
    }
    if (context.get("envelope") != null) {
        envelope = (String) context.get("envelope");
    }
    if (context.get(BF_REQUEST_URL_ATTRIBUTE) != null) {
        try {
            URI requestURI = new URI((String) context.get(BF_REQUEST_URL_ATTRIBUTE));
            requestURLHost = StringUtils.substringBefore(requestURI.toString(), requestURI.getHost())
                    + requestURI.getHost();
            LOGGER.info("bF requestURLHost= " + requestURLHost);
        } catch (URISyntaxException e) {
            LOGGER.warn("requestURL is not valid URL: " + context.get(BF_REQUEST_URL_ATTRIBUTE));
        }
    }
    if (context.get("fileId") != null) {
        fileId = Integer.valueOf((String) context.get("fileId"));
    }
    // http session attribute stored in betterform context
    if (context.get(BF_HTTP_SESSION_ATTRIBUTE) != null) {
        sessionId = (String) context.get(BF_HTTP_SESSION_ATTRIBUTE);
    }

    LOGGER.info("Get resource from XForm: " + uri);

    if (uri.startsWith(requestURLHost)) {
        // check if the request on the same (webq) host is done in the same session. Fix session id if required.
        if (sessionId != null) {
            validateSessionIdInRequestHeader(context, sessionId);
            LOGGER.info("Get resource from: " + uri);
        }
    } else {
        // add auth info only for URIs that are not on the same host.
        if (fileId != null && sessionId != null) {
            LOGGER.debug("Check if user is logged in to get resource for fileId=" + fileId);
            if (!context.containsKey(WEBQ_AUTH_ATTRIBUTE)) {
                // check if user is logged in - ask auth info from user_xml file table
                UserFile userFile = userFileService.getById(fileId);
                if (userFile.isAuthorized()) {
                    String authorizationInfo = userFile.getAuthorization();
                    String cookiesInfo = userFile.getCookies();
                    if (StringUtils.isNotEmpty(authorizationInfo)) {
                        authentication = "Authorization=" + authorizationInfo;
                    } else if (StringUtils.isNotEmpty(cookiesInfo)) {
                        authentication = "Cookie=" + cookiesInfo;
                    }
                }
                context.put(WEBQ_AUTH_ATTRIBUTE, authentication);
                LOGGER.debug("Store basic auth info in context for fileId=" + fileId);
            } else {
                // auth info stored in context
                authentication = context.get(WEBQ_AUTH_ATTRIBUTE) != null
                        ? (String) context.get(WEBQ_AUTH_ATTRIBUTE)
                        : null;
            }
            // add auth info only if user is logged in
            if (StringUtils.isNotEmpty(authentication)) {
                LOGGER.debug("User is logged in to get resource for fileId=" + fileId);

                String authAttribute = StringUtils.substringBefore(authentication, "=");

                // if the URI starts with instance or envelope URI, then we can use the basic auth retrieved from CDR.
                if (!"Cookie".equals(authAttribute)
                        && ((StringUtils.isNotBlank(instance) && uri.startsWith(instance))
                                || (StringUtils.isNotBlank(envelope) && uri.startsWith(envelope)))) {

                    String authAttributeValues = StringUtils.substringAfter(authentication, "=");
                    // prevent betterForm to overwrite cookies
                    /* Fall back to KnownHosts authorisation (qaaccount) if cookie auth mode is used.
                    // cookie mode does not work on test server.
                    if ("Cookie".equals(authAttribute)) {
                    if (context.containsKey(AbstractHTTPConnector.REQUEST_COOKIE)) {
                        context.remove(AbstractHTTPConnector.REQUEST_COOKIE);
                    }
                    }
                    */
                    httpRequestBase.addHeader(authAttribute, authAttributeValues);
                    LOGGER.info("Add " + authAttribute + " from session to URL: " + uri);
                } else {
                    // check if we have known host in db
                    KnownHost knownHost = knownHostsService.getKnownHost(uri);
                    if (knownHost != null) {
                        // add ticket parameter to request URI if needed
                        if (knownHost
                                .getAuthenticationMethod() == KnownHostAuthenticationMethod.REQUEST_PARAMETER) {
                            LOGGER.info("Add ticket parameter from known hosts to URL: " + uri);
                            uri = getUrlWithAuthParam(uri, knownHost);
                            if (!uri.equals(httpRequestBase.getURI().toString())) {
                                try {
                                    httpRequestBase.setURI(new URI(uri));
                                } catch (URISyntaxException e) {
                                    LOGGER.error("Unable to add known host ticket parameter for URI:" + uri);
                                    e.printStackTrace();
                                }
                            }
                        } else if (knownHost.getAuthenticationMethod() == KnownHostAuthenticationMethod.BASIC) {
                            // Add basic authorisation if needed
                            try {
                                LOGGER.info("Add basic auth from known hosts to URL: " + uri);
                                httpRequestBase.addHeader("Authorization", "Basic " + Base64.encodeBase64String(
                                        (knownHost.getKey() + ":" + knownHost.getTicket()).getBytes("utf-8"))
                                        .replaceAll("\n", ""));
                            } catch (UnsupportedEncodingException e) {
                                LOGGER.warn("UnsupportedEncodingException: utf-8");
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:net.jetrix.config.ServerConfig.java

/**
 * Save the configuration./*w w w .j a va 2s .c  om*/
 */
public void save() throws IOException {
    // todo make a backup copy of the previous configuration files

    // save the server.xml file
    PrintWriter out = null;

    try {
        File file = new File(serverConfigURL.toURI());
        out = new PrintWriter(file, ENCODING);
    } catch (URISyntaxException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

    out.println("<?xml version=\"1.0\"?>");
    out.println(
            "<!DOCTYPE tetrinet-server PUBLIC \"-//LFJR//Jetrix TetriNET Server//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-server.dtd\">");
    out.println();
    out.println("<tetrinet-server host=\"" + (host == null ? "[ALL]" : host.getHostAddress()) + "\">");
    out.println();
    out.println("  <!-- Server name -->");
    out.println("  <name>" + getName() + "</name>");
    out.println();
    out.println("  <!-- Server default language (using an ISO-639 two-letter language code) -->");
    out.println("  <language>" + getLocale().getLanguage() + "</language>");
    out.println();
    out.println("  <!-- How many seconds of inactivity before timeout occurs -->");
    out.println("  <timeout>" + getTimeout() + "</timeout>");
    out.println();
    out.println("  <!-- How many channels should be available on the server -->");
    out.println("  <max-channels>" + getMaxChannels() + "</max-channels>");
    out.println();
    out.println("  <!-- Maximum number of players on the server -->");
    out.println("  <max-players>" + getMaxPlayers() + "</max-players>");
    out.println();
    out.println("  <!-- Maximum number of simultaneous connections allowed from the same IP -->");
    out.println("  <max-connections>" + getMaxConnections() + "</max-connections>");
    out.println();
    out.println("  <!-- Typing /op <thispassword> will give player operator status -->");
    out.println("  <op-password>" + getOpPassword() + "</op-password>");
    out.println();
    out.println("  <!-- Use this password to log on the administration console -->");
    out.println("  <admin-password>" + getAdminPassword() + "</admin-password>");
    out.println();
    out.println("  <!-- Access Log, where requests are logged to -->");
    out.println("  <access-log path=\"" + getAccessLogPath() + "\" />");
    out.println();
    out.println("  <!-- Error Log, where errors are logged to -->");
    out.println("  <error-log  path=\"" + getErrorLogPath() + "\" />");
    out.println();
    out.println("  <!-- Path to the channels descriptor file (relative to the current configuration file) -->");
    out.println("  <channels path=\"" + getChannelsFile() + "\"/>");
    out.println();
    out.println("  <!-- Client listeners -->");
    out.println("  <listeners>");
    for (Listener listener : getListeners()) {
        String autostart = !listener.isAutoStart() ? " auto-start=\"false\"" : "";
        out.println("    <listener class=\"" + listener.getClass().getName() + "\" port=\"" + listener.getPort()
                + "\"" + autostart + "/>");
    }
    out.println("  </listeners>");
    out.println();

    out.println("  <!-- Services -->");
    out.println("  <services>");
    for (Service service : getServices()) {
        try {
            // get the parameters
            Map<String, Object> params = PropertyUtils.describe(service);

            String autostart = !service.isAutoStart() ? "auto-start=\"false\"" : "";
            String classname = "class=\"" + service.getClass().getName() + "\"";

            if (params.size() <= 4) {
                out.println("    <service " + classname + " " + autostart + "/>");
            } else {
                out.println("    <service " + classname + " " + autostart + ">");
                for (String param : params.keySet()) {
                    PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(service, param);
                    if (!"autoStart".equals(param) && desc.getWriteMethod() != null) {
                        out.println(
                                "      <param name=\"" + param + "\" value=\"" + params.get(param) + "\"/>");
                    }
                }
                out.println("    </service>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    out.println("  </services>");
    out.println();

    out.println("  <!-- Server commands -->");
    out.println("  <commands>");
    Iterator<Command> commands = CommandManager.getInstance().getCommands(AccessLevel.ADMINISTRATOR);
    while (commands.hasNext()) {
        try {
            Command command = commands.next();
            String hidden = command.isHidden() ? " hidden=\"true\"" : "";
            Command command2 = command.getClass().newInstance();
            String level = command2.getAccessLevel() != command.getAccessLevel()
                    ? " access-level=\"" + command.getAccessLevel() + "\""
                    : "";
            out.println("    <command class=\"" + command.getClass().getName() + "\"" + hidden + level + "/>");
        } catch (Exception e) {
            log.log(Level.WARNING, e.getMessage(), e);
        }
    }
    out.println("  </commands>");
    out.println();

    out.println("  <ban>");
    Iterator<Banlist.Entry> entries = Banlist.getInstance().getBanlist();
    while (entries.hasNext()) {
        Banlist.Entry entry = entries.next();
        out.println("    <host>" + entry.pattern + "</host>");
    }
    out.println("  </ban>");
    out.println();

    if (!datasources.isEmpty()) {
        out.println("  <!-- Database connection parameters -->");
        out.println("  <datasources>");
        out.println();

        for (DataSourceConfig datasource : datasources.values()) {
            out.println("    <datasource name=\"" + datasource.getName() + "\">");
            out.println("      <!-- The class of the JDBC driver used -->");
            out.println("      <driver>" + datasource.getDriver() + "</driver>");
            out.println();
            out.println("      <!-- The URL of the database (jdbc:<type>://<hostname>:<port>/<database>) -->");
            out.println("      <url>" + datasource.getUrl() + "</url>");
            out.println();
            out.println("      <!-- The username connecting to the database -->");
            out.println("      <username>" + datasource.getUsername() + "</username>");
            out.println();
            out.println("      <!-- The password of the user -->");
            if (datasource.getPassword() != null) {
                out.println("      <password>" + datasource.getPassword() + "</password>");
            } else {
                out.println("      <password/>");
            }
            if (datasource.getMinIdle() != DataSourceManager.DEFAULT_MIN_IDLE) {
                out.println();
                out.println("      <!-- The minimum number of idle connections -->");
                out.println("      <min-idle>" + datasource.getMinIdle() + "</min-idle>");
            }
            if (datasource.getMaxActive() != DataSourceManager.DEFAULT_MAX_ACTIVE) {
                out.println();
                out.println("      <!-- The maximum number of active connections -->");
                out.println("      <max-active>" + datasource.getMaxActive() + "</max-active>");
            }
            out.println("    </datasource>");
            out.println();
        }
        out.println("  </datasources>");
        out.println();
    }

    if (mailSessionConfig != null) {
        StringBuilder buffer = new StringBuilder();
        buffer.append("  <mailserver host=\"").append(mailSessionConfig.getHostname()).append("\"");
        buffer.append(" port=\"").append(mailSessionConfig.getPort()).append("\"");
        if (mailSessionConfig.isAuth()) {
            buffer.append(" auth=\"true\"");
            buffer.append(" username=\"").append(mailSessionConfig.getUsername()).append("\"");
            buffer.append(" password=\"").append(mailSessionConfig.getPassword()).append("\"");
        }
        if (mailSessionConfig.isDebug()) {
            buffer.append(" debug=\"true\"");
        }
        buffer.append("/>");

        out.println("  <!-- Mail server parameters -->");
        out.println(buffer.toString());
        out.println();
    }

    if (properties != null && !properties.isEmpty()) {
        out.println("  <!-- Extended properties -->");
        out.println("  <properties>");
        for (String key : properties.stringPropertyNames()) {
            out.println("    <property name=\"" + key + "\" value=\"" + properties.getProperty(key) + "\">");
        }
        out.println("  </properties>");
        out.println();
    }

    out.println("</tetrinet-server>");

    out.flush();
    out.close();

    // save the channels.xml file
    try {
        File file = new File(channelsConfigURL.toURI());
        out = new PrintWriter(file, ENCODING);
    } catch (URISyntaxException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

    out.println("<?xml version=\"1.0\"?>");
    out.println(
            "<!DOCTYPE tetrinet-channels PUBLIC \"-//LFJR//Jetrix Channels//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-channels.dtd\">");
    out.println();
    out.println("<tetrinet-channels>");
    out.println();
    out.println("  <!-- Message Of The Day -->");
    out.println("  <motd><![CDATA[");
    out.println(getMessageOfTheDay());
    out.println("  ]]></motd>");
    out.println();

    // filter definitions
    Map<String, String> aliases = FilterManager.getInstance().getFilterAliases();
    out.println("  <!-- Channel filters -->");
    out.println("  <filter-definitions>");
    for (String alias : aliases.keySet()) {
        out.println("    <alias name=\"" + alias + "\" class=\"" + aliases.get(alias) + "\"/>");
    }
    out.println("  </filter-definitions>");
    out.println();

    // global filters
    out.println("  <!-- Global filters -->");
    out.println("  <default-filters>");
    for (FilterConfig filter : globalFilters) {
        saveFilter(filter, out, "    ");
    }
    out.println("  </default-filters>");
    out.println();

    // winlists
    out.println("  <!-- Winlists -->");
    out.println("  <winlists>");
    for (Winlist winlist : WinlistManager.getInstance().getWinlists()) {
        WinlistConfig config = winlist.getConfig();
        Properties props = config.getProperties();
        if (props == null || props.isEmpty()) {
            out.println("    <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName()
                    + "\"/>");
        } else {
            out.println("    <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName()
                    + "\">");
            for (Object name : props.keySet()) {
                out.println("      <param name=\"" + name + "\" value=\"" + props.get(name) + "\"/>");
            }
            out.println("    </winlist>");
        }
    }
    out.println("  </winlists>");
    out.println();

    // default settings
    Settings settings = Settings.getDefaultSettings();

    out.println("  <!-- Default game settings -->");
    out.println("  <default-settings>");
    out.println("    <!-- What level each player starts at -->");
    out.println("    <starting-level>" + settings.getStartingLevel() + "</starting-level>");
    out.println();
    out.println("    <!-- How many lines to make before player level increases -->");
    out.println("    <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>");
    out.println();
    out.println("    <!-- Number of levels to increase each time -->");
    out.println("    <level-increase>" + settings.getLevelIncrease() + "</level-increase>");
    out.println();
    out.println("    <!-- Lines to make to get a special block -->");
    out.println("    <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>");
    out.println();
    out.println("    <!-- Number of special blocks added each time -->");
    out.println("    <special-added>" + settings.getSpecialAdded() + "</special-added>");
    out.println();
    out.println("    <!-- Capacity of Special block inventory -->");
    out.println("    <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>");
    out.println();
    out.println("    <!-- Play by classic rules? -->");
    out.println("    <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>");
    out.println();
    out.println("    <!-- Average together all player's game level? -->");
    out.println(
            "    <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>");
    out.println();
    out.println("    <!-- Same sequence of blocks for all players? (tetrinet 1.14 clients only) -->");
    out.println("    <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>");
    out.println();
    out.println("    <block-occurancy>");
    for (Block block : Block.values()) {
        out.println("      <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode()
                + ">");
    }
    out.println("    </block-occurancy>");
    out.println();
    out.println("    <special-occurancy>");
    for (Special special : Special.values()) {
        out.println("      <" + special.getCode() + ">" + settings.getOccurancy(special) + "</"
                + special.getCode() + ">");
    }
    out.println("    </special-occurancy>");
    out.println();
    out.println("    <!-- Sudden death parameters -->");
    out.println("    <sudden-death>");
    out.println("      <!-- Time in seconds before the sudden death begins, 0 to disable the sudden death -->");
    out.println("      <time>" + settings.getSuddenDeathTime() + "</time>");
    out.println();
    out.println(
            "      <!-- The message displayed when the sudden death begins. Use \"key:\" prefix to display an internationalized message -->");
    out.println("      <message>" + settings.getSuddenDeathMessage() + "</message>");
    out.println();
    out.println("      <!-- The delay in seconds between lines additions -->");
    out.println("      <delay>" + settings.getSuddenDeathDelay() + "</delay>");
    out.println();
    out.println("      <!-- The number of lines added -->");
    out.println("      <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>");
    out.println("    </sudden-death>");
    out.println();
    out.println("  </default-settings>");
    out.println();
    out.println();

    out.println("  <channels>");
    for (Channel channel : ChannelManager.getInstance().channels()) {
        ChannelConfig config = channel.getConfig();

        if (config.isPersistent()) {
            out.println("    <channel name=\"" + config.getName() + "\">");
            if (config.getDescription() != null) {
                String description = config.getDescription();
                description = description.contains("<") ? "<![CDATA[" + description + "]]>" : description;
                out.println("      <description>" + description + "</description>");
            }

            if (config.getTopic() != null && config.getTopic().trim().length() > 0) {
                out.println("      <topic>");
                out.println("<![CDATA[");
                out.println(config.getTopic());
                out.println("]]>");
                out.println("      </topic>");
            }

            if (config.getSpeed() != Speed.MIXED) {
                out.println("      <speed>" + config.getSpeed().name().toLowerCase() + "</speed>");
            }

            if (config.isPasswordProtected()) {
                out.println("      <password>" + config.getPassword() + "</password>");
            }

            if (config.getAccessLevel() != AccessLevel.PLAYER) {
                out.println("      <access-level>" + config.getAccessLevel() + "</access-level>");
            }

            if (config.isIdleAllowed()) {
                out.println("      <idle>true</idle>");
            }

            if (!config.isVisible()) {
                out.println("      <visible>false</visible>");
            }

            if (config.getMaxPlayers() != ChannelConfig.PLAYER_CAPACITY) {
                out.println("      <max-players>" + config.getMaxPlayers() + "</max-players>");
            }

            if (config.getMaxSpectators() != ChannelConfig.SPECTATOR_CAPACITY) {
                out.println("      <max-spectators>" + config.getMaxSpectators() + "</max-spectators>");
            }

            if (config.getWinlistId() != null) {
                out.println("      <winlist name=\"" + config.getWinlistId() + "\"/>");
            }

            // channel settings
            settings = config.getSettings();
            if (!settings.useDefaultSettings()) {
                out.println("      <settings>");
                if (!settings.isDefaultStartingLevel()) {
                    out.println("        <starting-level>" + settings.getStartingLevel() + "</starting-level>");
                }
                if (!settings.isDefaultLinesPerLevel()) {
                    out.println(
                            "        <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>");
                }
                if (!settings.isDefaultLevelIncrease()) {
                    out.println("        <level-increase>" + settings.getLevelIncrease() + "</level-increase>");
                }
                if (!settings.isDefaultLinesPerSpecial()) {
                    out.println("        <lines-per-special>" + settings.getLinesPerSpecial()
                            + "</lines-per-special>");
                }
                if (!settings.isDefaultSpecialAdded()) {
                    out.println("        <special-added>" + settings.getSpecialAdded() + "</special-added>");
                }
                if (!settings.isDefaultSpecialCapacity()) {
                    out.println("        <special-capacity>" + settings.getSpecialCapacity()
                            + "</special-capacity>");
                }
                if (!settings.isDefaultClassicRules()) {
                    out.println("        <classic-rules>" + (settings.getClassicRules() ? "true" : "false")
                            + "</classic-rules>");
                }
                if (!settings.isDefaultAverageLevels()) {
                    out.println("        <average-levels>" + (settings.getAverageLevels() ? "true" : "false")
                            + "</average-levels>");
                }
                if (!settings.isDefaultSameBlocks()) {
                    out.println("        <same-blocks>" + (settings.getSameBlocks() ? "true" : "false")
                            + "</same-blocks>");
                }

                if (!settings.isDefaultBlockOccurancy()) {
                    out.println("        <block-occurancy>");
                    for (Block block : Block.values()) {
                        if (settings.getOccurancy(block) != 0) {
                            out.println("          <" + block.getCode() + ">" + settings.getOccurancy(block)
                                    + "</" + block.getCode() + ">");
                        }

                    }
                    out.println("        </block-occurancy>");
                }

                if (!settings.isDefaultSpecialOccurancy()) {
                    out.println("        <special-occurancy>");
                    for (Special special : Special.values()) {
                        if (settings.getOccurancy(special) != 0) {
                            out.println("          <" + special.getCode() + ">" + settings.getOccurancy(special)
                                    + "</" + special.getCode() + ">");
                        }
                    }
                    out.println("        </special-occurancy>");
                }

                // sudden death settings
                if (!settings.isDefaultSuddenDeath()) {
                    out.println("        <sudden-death>");
                    if (!settings.isDefaultSuddenDeathTime()) {
                        out.println("          <time>" + settings.getSuddenDeathTime() + "</time>");
                    }
                    if (!settings.isDefaultSuddenDeathMessage()) {
                        out.println("          <message>" + settings.getSuddenDeathMessage() + "</message>");
                    }
                    if (!settings.isDefaultSuddenDeathDelay()) {
                        out.println("          <delay>" + settings.getSuddenDeathDelay() + "</delay>");
                    }
                    if (!settings.isDefaultSuddenDeathLinesAdded()) {
                        out.println("          <lines-added>" + settings.getSuddenDeathLinesAdded()
                                + "</lines-added>");
                    }
                    out.println("        </sudden-death>");
                }

                out.println("      </settings>");
            }

            // local filters
            Collection<MessageFilter> filters = channel.getLocalFilters();
            if (!filters.isEmpty()) {
                out.println("      <filters>");
                for (MessageFilter filter : filters) {
                    saveFilter(filter.getConfig(), out, "        ");
                }
                out.println("      </filters>");
            }

            out.println("    </channel>");
            out.println();
        }
    }

    out.println("  </channels>");
    out.println();
    out.println("</tetrinet-channels>");

    out.close();
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;//from  w w w.j  ava  2 s .  co  m

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:uk.co.ashtonbrsc.intentexplode.Explode.java

private Intent cloneIntent(String intentUri) {
    if (intentUri != null) {
        try {//from   ww  w.  j  a v  a2  s . com
            Intent clone = Intent.parseUri(intentUri, Intent.URI_INTENT_SCHEME);

            // bugfix #14: restore extras that are lost in the intent <-> string conversion
            if (additionalExtras != null) {
                clone.putExtras(additionalExtras);
            }

            return clone;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    return null;
}