Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java

private void processFramesSubPage(ProcessedPage subPage, String subPageUrl, WebClientOrigin origin)
        throws IOException, ParameterException, ResourceException, StorageException {
    boolean processingSubPage = false;
    try {/*from   ww w .  j  a  v a  2  s. co  m*/
        String oldBaseUrl = getPageLinksForCurrentContext().getBaseUrl();
        String newSubPageUrl = null;

        if (subPage == null) {
            // HtmlUnit shows about:blank frame page when it can't
            // follow it (i.e. when it is ftp:// or another protocol).
            String reasonFailed = "";
            if (!subPageUrl.isEmpty()) {
                // Frame has not been followed, so we have to use url from
                // source, not from page.
                // In most cases that means protocol was not supported.
                try {
                    Link frameUrlFromSource = new Link(oldBaseUrl, subPageUrl);
                    newSubPageUrl = frameUrlFromSource.getAbsoluteUrl();
                    reasonFailed = "Unable to follow url from " + origin.getName();
                } catch (URISyntaxException e) {
                    // This is unlikely to happen.
                    LOGGER.debug("Can't create Link for subpage: " + e.getMessage(), e);
                    reasonFailed = "Can't create Link for " + origin.getName();
                    newSubPageUrl = "about:blank";
                }
            } else {
                reasonFailed = "Src for " + origin.getName() + " is empty.";
                newSubPageUrl = "about:blank";
            }
            processingSubPage = prepareSubPage(newSubPageUrl, origin);
            if (processingSubPage) {
                addRequiredAttributesToCurrentContext(reasonFailed);
            }
        } else {
            newSubPageUrl = subPage.getActualUrl().toExternalForm();
            processingSubPage = prepareSubPage(newSubPageUrl, origin);
            if (processingSubPage) {
                processPage(subPage);
            }
        }
    } catch (ContextSizeLimitExceededException e) {
        LOGGER.debug("Couldn't open subcontext: size limit reached: {}", e.getMessage());
        processingSubPage = false;
    } catch (URIException e) {
        // Protocol not supported, but object has to be created and url_original set.
        LOGGER.debug("Protocol not supported (not HTTP/HTTPS) for iframe:" + e.getMessage());
        ctx.addAttribute(URL_ORIGINAL_STRING, e.getMessage());
    } finally {
        if (processingSubPage) {
            ctx.closeSubContext();
        }
    }
}

From source file:jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnectorImpl.java

private Promise<CloudStorageAccount, Throwable, Void> getStorageAccountAsync(final String storage) {
    return getStorageAccountsAsync()
            .then(new DonePipe<List<StorageAccount>, List<StorageAccountKey>, Throwable, Void>() {
                @Override//w  ww .  j  av a  2 s.  c  om
                public Promise<List<StorageAccountKey>, Throwable, Void> pipeDone(
                        List<StorageAccount> accounts) {
                    final StorageAccount account = CollectionsUtil.findFirst(accounts,
                            new Filter<StorageAccount>() {
                                @Override
                                public boolean accept(@NotNull StorageAccount account) {
                                    return account.name().equalsIgnoreCase(storage);
                                }
                            });

                    if (account == null) {
                        final String message = String.format("Storage account %s not found", storage);
                        LOG.debug(message);
                        return new DeferredObject<List<StorageAccountKey>, Throwable, Void>()
                                .reject(new CloudException(message));
                    }

                    if (!account.regionName().equalsIgnoreCase(myLocation)) {
                        final String message = String.format(
                                "VHD image should be located in storage account in the %s region", myLocation);
                        LOG.debug(message);
                        return new DeferredObject<List<StorageAccountKey>, Throwable, Void>()
                                .reject(new CloudException(message));
                    }

                    final Matcher groupMatcher = RESOURCE_GROUP_PATTERN.matcher(account.id());
                    if (!groupMatcher.find()) {
                        final String message = String.format("Invalid storage account identifier %s",
                                account.id());
                        LOG.debug(message);
                        return new DeferredObject<List<StorageAccountKey>, Throwable, Void>()
                                .reject(new CloudException(message));
                    }

                    return getStorageAccountKeysAsync(groupMatcher.group(1), storage);
                }
            }).then(new DonePipe<List<StorageAccountKey>, CloudStorageAccount, Throwable, Void>() {
                @Override
                public Promise<CloudStorageAccount, Throwable, Void> pipeDone(List<StorageAccountKey> keys) {
                    final DeferredObject<CloudStorageAccount, Throwable, Void> deferred = new DeferredObject<>();
                    try {
                        deferred.resolve(new CloudStorageAccount(
                                new StorageCredentialsAccountAndKey(storage, keys.get(0).value())));
                    } catch (URISyntaxException e) {
                        final String message = String.format("Invalid storage account %s credentials: %s",
                                storage, e.getMessage());
                        LOG.debug(message);
                        final CloudException exception = new CloudException(message, e);
                        deferred.reject(exception);
                    }

                    return deferred;
                }
            });
}

From source file:com.inamik.template.TemplateEngine.java

/**
 * getURLModifiedTime (private) - Tries to determine the last modified
 * time of the specified URL.  If the URL is not a file, then it returns
 * TemplateEngine.TEMPLATE_START_TIME//from   w  ww.  ja  v a2  s. co m
 * @param url
 * @return Last modified time of the specified URL
 * @throws FileNotFoundException
 * @see {@link TemplateEngine#TEMPLATE_START_TIME}
 */
private long getURLModifiedTime(final URL url) throws FileNotFoundException {
    final long lastModifiedTime;

    if (PROTOCOL_FILE.equals(url.getProtocol()) == true) {
        if (LOG.isDebugEnabled())
            LOG.debug(
                    "Resource uses protocol " + PROTOCOL_FILE + ", looking for lastModified: " + url.getPath());

        try {
            File file = new File(url.toURI());

            lastModifiedTime = file.lastModified();

            if (LOG.isDebugEnabled())
                LOG.debug("Resource has lastModified of " + lastModifiedTime + ": " + url.getPath());
        } catch (URISyntaxException e) {
            if (LOG.isWarnEnabled())
                LOG.warn("Unexpected URISyntaxException for resource: " + url.getPath(), e);

            throw new FileNotFoundException(e.getMessage());
        }
    } else {
        lastModifiedTime = TEMPLATE_START_TIME;
    }

    return lastModifiedTime;
}

From source file:edu.jhu.pha.vosync.rest.DropboxService.java

@Path("chunked_upload")
@PUT//www  . jav a2s .  c  o m
@RolesAllowed({ "user", "rwshareuser" })
public Response chunkedUpload(@QueryParam("upload_id") String uploadId, @QueryParam("offset") long offset,
        InputStream fileDataInp) {
    final SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());
    VoSyncMetaStore voMeta = new VoSyncMetaStore(user.getName());

    logger.debug("New chunk: " + uploadId + " " + offset);

    if (null == uploadId) {
        uploadId = RandomStringUtils.randomAlphanumeric(15);
    }

    Chunk newChunk = voMeta.getLastChunk(uploadId);

    if (offset != newChunk.getChunkStart()) { // return error with proper offset
        logger.error("Wrong offset: " + offset + " should be:" + newChunk.getChunkStart());
        ResponseBuilder errorResp = Response.status(400);
        errorResp.entity(genChunkResponse(uploadId, newChunk.getChunkStart()));
        return errorResp.build();
    }

    VospaceId identifier;
    try {

        String chunkNumberString = String.format("%07d", newChunk.getChunkNum());

        identifier = new VospaceId(new NodePath(
                "/" + conf.getString("chunked_container") + "/" + uploadId + "/" + chunkNumberString));
        DataNode node = (DataNode) NodeFactory.createNode(identifier, user.getName(), NodeType.DATA_NODE);

        node.getStorage().createContainer(new NodePath("/" + conf.getString("chunked_container")));
        node.getStorage().putBytes(identifier.getNodePath(), fileDataInp);

        NodeInfo info = new NodeInfo();

        node.getStorage().updateNodeInfo(identifier.getNodePath(), info);
        node.setNodeInfo(info);

        newChunk.setSize(info.getSize());

        voMeta.putNewChunk(newChunk);

        byte[] resp = genChunkResponse(uploadId, newChunk.getChunkStart() + newChunk.getSize());

        return Response.ok(resp).build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e.getMessage());
    }

}

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    Args.notNull(response, "HTTP response");
    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }/*from  w ww  . ja  v  a2 s . com*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri;
    try {
        uri = new URI(location);
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    final HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        final HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Asserts.notNull(target, "Target host");

        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (final URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        final URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnectorImpl.java

/**
 * Deletes a cloud instance./*from   w w  w . j a  v  a 2 s.  c om*/
 *
 * @param instance is a cloud instance.
 * @return promise.
 */
@NotNull
@Override
public Promise<Void, Throwable, Void> deleteVmAsync(@NotNull final AzureCloudInstance instance) {
    final String name = instance.getName();
    return deleteResourceGroupAsync(instance.getName())
            .then(new DonePipe<Void, List<CloudBlob>, Throwable, Void>() {
                @Override
                public Promise<List<CloudBlob>, Throwable, Void> pipeDone(Void result) {
                    final String url = instance.getImage().getImageDetails().getImageUrl();
                    final URI storageBlobs;
                    try {
                        final URI imageUrl = new URI(url);
                        storageBlobs = new URI(imageUrl.getScheme(), imageUrl.getHost(), "/vhds/" + name, null);
                    } catch (URISyntaxException e) {
                        final String message = String.format(
                                "Failed to parse VHD image URL %s for instance %s: %s", url, name,
                                e.getMessage());
                        LOG.debug(message, e);
                        final CloudException exception = new CloudException(message, e);
                        return new DeferredObject<List<CloudBlob>, Throwable, Void>().reject(exception);
                    }

                    return getBlobsAsync(storageBlobs);
                }
            }).then(new DonePipe<List<CloudBlob>, Void, Throwable, Void>() {
                @Override
                public Promise<Void, Throwable, Void> pipeDone(List<CloudBlob> blobs) {
                    for (CloudBlob blob : blobs) {
                        try {
                            blob.deleteIfExists();
                        } catch (Exception e) {
                            final String message = String.format("Failed to delete blob %s for instance %s: %s",
                                    blob.getUri(), name, e.getMessage());
                            LOG.warnAndDebugDetails(message, e);
                        }
                    }

                    return new DeferredObject<Void, Throwable, Void>().resolve(null);
                }
            });
}

From source file:la.alsocan.symbiot.access.DriverDao.java

public DriverDao(ObjectMapper om) {

    // open drivers folder
    String jarFolder;/* ww  w.j  av  a  2  s.  c  om*/
    try {
        URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
        File jarFile = new File(url.toURI());
        jarFolder = jarFile.getParentFile().getPath();
    } catch (URISyntaxException ex) {
        jarFolder = "<unable to resolve>";
    }
    String driverFolderPath = jarFolder + File.separatorChar + DRIVER_FOLDER_NAME;
    File folder = new File(driverFolderPath);
    if (!folder.exists() || !folder.isDirectory()) {
        throw new IllegalStateException("Could not find folder '" + driverFolderPath + "'");
    }

    // load drivers in memory
    drivers = new LinkedHashMap<>();
    for (File file : folder.listFiles((File dir, String name) -> {
        return name.endsWith(".json");
    })) {
        DriverTo to;
        try {
            to = om.readValue(file, DriverTo.class);
            if (!drivers.containsKey(to.getId())) {
                drivers.put(to.getId(), to);
            } else {
                LOG.warn("The driver file '" + file.getName() + "' uses a conflicting ID '" + to.getId() + "'");
                LOG.info("Check driver with name '" + drivers.get(to.getId()).getName()
                        + "' to resolve conflict");
                LOG.info("Driver file '" + file.getName() + "' will not be loaded");
            }
        } catch (IOException ex) {
            LOG.warn("Malformed driver '" + file.getName() + "': " + ex.getMessage());
            LOG.info("Driver '" + file.getName() + "' will not be loaded");
        }
    }
}

From source file:com.mongolduu.android.ng.misc.RedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/* w w  w  . j av  a2 s .c  o m*/
    // get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    // HERE IS THE MODIFIED LINE OF CODE
    String location = locationHeader.getValue().replaceAll(" ", "%20");

    URI uri;
    try {
        uri = new URI(location);
    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

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

/**
 * Save the configuration./*  w  w  w . java 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();
}