Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:info.varden.anatychia.Main.java

public static MaterialDataList materialList(SaveData save, ProgressUpdater pu, MaterialData[] filters) {
    Random random = new Random();
    boolean filtersNull = filters == null;
    pu.updated(0, 1);/* w  w w.  j ava 2s.  co m*/
    pu.updated(-3, 1);
    MaterialDataList mdl = new MaterialDataList();
    File saveDir = save.getLocation();
    File[] regionFolders = listRegionContainers(saveDir);
    int depth = Integer.MAX_VALUE;
    File shallowest = null;
    for (File f : regionFolders) {
        String path = f.getAbsolutePath();
        Pattern p = Pattern.compile(Pattern.quote(File.separator));
        Matcher m = p.matcher(path);
        int count = 0;
        while (m.find()) {
            count++;
        }
        if (count < depth) {
            depth = count;
            if (shallowest == null || f.getName().equalsIgnoreCase("region")) {
                shallowest = f;
            }
        }
    }
    pu.updated(-1, 1);
    ArrayList<File> regions = new ArrayList<File>();
    int tfs = 0;
    for (File f : regionFolders) {
        String dimName = f.getParentFile().getName();
        boolean deleted = false;
        if (f.equals(shallowest)) {
            dimName = "DIM0";
        }
        if (!filtersNull) {
            for (MaterialData type : filters) {
                if (type.getType() == MaterialType.DIMENSION && type.getName().equals(dimName)) {
                    System.out.println("Deleting: " + dimName);
                    deleted = recursiveDelete(f);
                }
            }
        }
        if (deleted)
            continue;
        mdl.increment(new MaterialData(MaterialType.DIMENSION, dimName, 1L));
        File[] r = f.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mca");
            }

        });
        int max = r.length;
        int cur = 0;
        for (File valid : r) {
            cur++;
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(valid));
                byte[] offsetHeader = new byte[4096];
                bis.read(offsetHeader, 0, 4096);
                bis.close();
                ByteBuffer bb = ByteBuffer.wrap(offsetHeader);
                IntBuffer ib = bb.asIntBuffer();
                while (ib.remaining() > 0) {
                    if (ib.get() != 0) {
                        tfs++;
                    }
                }
                bb = null;
                ib = null;
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            // tfs += Math.floor(valid.length() / 1000D);
            pu.updated(cur, max);
        }
        regions.addAll(Arrays.asList(r));
    }
    if (regions.size() <= 0) {
        pu.updated(1, 1);
        return mdl;
    }
    pu.updated(-2, 1);
    int fc = 0;
    int fs = 0;
    for (File region : regions) {
        fc++;
        //fs += Math.floor(region.length() / 1000D);
        try {
            RegionFile anvil = new RegionFile(region);
            for (int x = 0; x < 32; x++) {
                for (int z = 0; z < 32; z++) {
                    InputStream is = anvil.getChunkDataInputStream(x, z);
                    if (is == null)
                        continue;
                    NBTInputStream nbti = new NBTInputStream(is, CompressionMode.NONE);
                    CompoundTag root = (CompoundTag) nbti.readTag();
                    String rootName = root.getName();
                    CompoundTag level = (CompoundTag) root.getValue().get("Level");
                    Map<String, Tag> levelTags = level.getValue();
                    ListTag sectionTag = (ListTag) levelTags.get("Sections");
                    ArrayList<Tag> sections = new ArrayList<Tag>(sectionTag.getValue());
                    for (int i = 0; i < sections.size(); i++) {
                        mdl.setSectorsRelative(1);
                        CompoundTag sect = (CompoundTag) sections.get(i);
                        Map<String, Tag> sectTags = sect.getValue();
                        ByteArrayTag blockArray = (ByteArrayTag) sectTags.get("Blocks");
                        byte[] add = new byte[0];
                        boolean hasAdd = false;
                        if (sectTags.containsKey("Add")) {
                            hasAdd = true;
                            ByteArrayTag addArray = (ByteArrayTag) sectTags.get("Add");
                            add = addArray.getValue();
                        }
                        byte[] blocks = blockArray.getValue();
                        for (int j = 0; j < blocks.length; j++) {
                            short id;
                            byte aid = (byte) 0;
                            if (hasAdd) {
                                aid = ChunkFormat.Nibble4(add, j);
                                id = (short) ((blocks[j] & 0xFF) + (aid << 8));
                            } else {
                                id = (short) (blocks[j] & 0xFF);
                            }
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.BLOCK
                                            && type.getName().equals(String.valueOf(blocks[j] & 0xFF))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        blocks[j] = (byte) 0;
                                        if (aid != 0) {
                                            add[j / 2] = (byte) (add[j / 2] & (j % 2 == 0 ? 0xF0 : 0x0F));
                                        }
                                        id = (short) 0;
                                    }
                                }
                            }
                            mdl.increment(new MaterialData(MaterialType.BLOCK, String.valueOf(id), 1L));
                        }
                        if (!filtersNull) {
                            HashMap<String, Tag> rSectTags = new HashMap<String, Tag>();
                            rSectTags.putAll(sectTags);
                            ByteArrayTag bat = new ByteArrayTag("Blocks", blocks);
                            rSectTags.put("Blocks", bat);
                            if (hasAdd) {
                                ByteArrayTag adt = new ByteArrayTag("Add", add);
                                rSectTags.put("Add", adt);
                            }
                            CompoundTag rSect = new CompoundTag(sect.getName(), rSectTags);
                            sections.set(i, rSect);
                        }
                    }
                    ListTag entitiesTag = (ListTag) levelTags.get("Entities");
                    ArrayList<Tag> entities = new ArrayList<Tag>(entitiesTag.getValue());
                    for (int i = entities.size() - 1; i >= 0; i--) {
                        CompoundTag entity = (CompoundTag) entities.get(i);
                        Map<String, Tag> entityTags = entity.getValue();
                        if (entityTags.containsKey("id")) {
                            StringTag idTag = (StringTag) entityTags.get("id");
                            String id = idTag.getValue();
                            boolean removed = false;
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.ENTITY
                                            && (type.getName().equals(id) || type.getName().equals(""))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        if (type.fulfillsRequirements(entity)) {
                                            entities.remove(i);
                                            removed = true;
                                        }
                                    }
                                }
                            }
                            if (!removed) {
                                mdl.increment(new MaterialData(MaterialType.ENTITY, id, 1L));
                            }
                        }
                    }
                    nbti.close();
                    is.close();
                    if (!filtersNull) {
                        HashMap<String, Tag> rLevelTags = new HashMap<String, Tag>();
                        rLevelTags.putAll(levelTags);
                        ListTag rSectionTag = new ListTag("Sections", CompoundTag.class, sections);
                        rLevelTags.put("Sections", rSectionTag);
                        ListTag rEntityTag = new ListTag("Entities", CompoundTag.class, entities);
                        rLevelTags.put("Entities", rEntityTag);
                        final CompoundTag rLevel = new CompoundTag("Level", rLevelTags);
                        HashMap<String, Tag> rRootTags = new HashMap<String, Tag>() {
                            {
                                put("Level", rLevel);
                            }
                        };
                        CompoundTag rRoot = new CompoundTag(rootName, rRootTags);
                        OutputStream os = anvil.getChunkDataOutputStream(x, z);
                        NBTOutputStream nbto = new NBTOutputStream(os, CompressionMode.NONE);
                        nbto.writeTag(rRoot);
                        nbto.close();
                    }
                    fs++;
                    pu.updated(fs, tfs);
                }
            }
            anvil.close();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MaterialData[] data = mdl.toArray();
    System.out.println("FILES SCANNED: " + fc);
    for (MaterialData d : data) {
        System.out.println(d.getType().getName() + ": " + d.getName() + " (" + d.getQuantity() + ")");
    }
    return mdl;
}

From source file:io.wcm.wcm.parsys.componentinfo.impl.OsgiParsysConfigProvider.java

@Activate
private void activate(ComponentContext componentContext) {
    @SuppressWarnings("unchecked")
    final Dictionary<String, Object> props = componentContext.getProperties();

    // read config properties
    this.pageComponentPath = PropertiesUtil.toString(props.get(PROPERTY_PAGE_COMPONENT_PATH), null);
    String path = PropertiesUtil.toString(props.get(PROPERTY_PATH), null);
    String patternString = PropertiesUtil.toString(props.get(PROPERTY_PATH_PATTERN), null);
    String[] allowedChildrenArray = PropertiesUtil.toStringArray(props.get(PROPERTY_ALLOWED_CHILDREN), null);
    String[] deniedChildrenArray = PropertiesUtil.toStringArray(props.get(PROPERTY_DENIED_CHILDREN), null);
    String[] allowedParentsArray = PropertiesUtil.toStringArray(props.get(PROPERTY_ALLOWED_PARENTS), null);
    this.parentAncestorLevel = PropertiesUtil.toInteger(props.get(PROPERTY_PARENT_ANCESTOR_LEVEL),
            DEFAULT_PARENT_ANCESTOR_LEVEL);

    // set path pattern if any
    if (StringUtils.isNotEmpty(patternString)) {
        this.pathPattern = Pattern.compile(patternString);
    }/*from  w w  w  .j ava2s .c om*/
    // alternative: use path to build a pattern
    else if (StringUtils.isNotBlank(path)) {
        // path may also contain a simple node name
        if (!StringUtils.startsWith(path, JcrConstants.JCR_CONTENT + "/")) {
            path = JcrConstants.JCR_CONTENT + "/" + path; //NOPMD
        }
        this.pathPattern = Pattern.compile("^" + Pattern.quote(path) + "$");
    }

    // set allowed children
    Set<String> allowedChildrenSet = new HashSet<>();
    if (allowedChildrenArray != null) {
        for (String resourceType : allowedChildrenArray) {
            if (StringUtils.isNotBlank(resourceType)) {
                allowedChildrenSet.add(resourceType);
            }
        }
    }
    this.allowedChildren = ImmutableSet.copyOf(allowedChildrenSet);

    // set denied children
    Set<String> deniedChildrenSet = new HashSet<>();
    if (deniedChildrenArray != null) {
        for (String resourceType : deniedChildrenArray) {
            if (StringUtils.isNotBlank(resourceType)) {
                deniedChildrenSet.add(resourceType);
            }
        }
    }
    this.deniedChildren = ImmutableSet.copyOf(deniedChildrenSet);

    // set allowed parents
    Set<String> allowedParentsSet = new HashSet<>();
    if (allowedParentsArray != null) {
        for (String resourceType : allowedParentsArray) {
            if (StringUtils.isNotBlank(resourceType)) {
                allowedParentsSet.add(resourceType);
            }
        }
    }
    this.allowedParents = ImmutableSet.copyOf(allowedParentsSet);

    if (log.isDebugEnabled()) {
        log.debug(
                getClass().getSimpleName() + ": " + PROPERTY_PAGE_COMPONENT_PATH + "={}, " + PROPERTY_PATH
                        + "={}, " + PROPERTY_PATH_PATTERN + "={}, " + PROPERTY_ALLOWED_CHILDREN + "={}, "
                        + PROPERTY_DENIED_CHILDREN + "={}, " + PROPERTY_ALLOWED_PARENTS + "={}, "
                        + PROPERTY_PARENT_ANCESTOR_LEVEL + "={}",
                new Object[] { this.pageComponentPath, path, this.pathPattern, this.allowedChildren,
                        this.deniedChildren, this.allowedParents, this.parentAncestorLevel });
    }

    // validation messages
    if (StringUtils.isBlank(this.pageComponentPath)) {
        log.warn(
                PROPERTY_PAGE_COMPONENT_PATH + " cannot be null or empty. This configuration will be ignored.");
    }
    if (this.pathPattern == null) {
        log.warn("Path pattern cannot be null. Please set the property " + PROPERTY_PATH_PATTERN + " or "
                + PROPERTY_PATH);
    }
}

From source file:com.epam.ta.reportportal.database.dao.UserRepositoryCustomImpl.java

@Override
public Page<User> searchForUserLogin(String term, Pageable pageable) {
    final String regex = "(?i).*" + Pattern.quote(term.toLowerCase()) + ".*";
    Criteria login = where(LOGIN).regex(regex);
    Criteria fullName = where(FULLNAME_DB_FIELD).regex(regex);
    Criteria criteria = new Criteria().orOperator(login, fullName);
    Query query = query(criteria).with(pageable);
    query.fields().include(LOGIN);/*  ww  w .j a v  a2 s . co m*/
    query.fields().include(FULLNAME_DB_FIELD);
    List<User> users = mongoOperations.find(query, User.class);
    return new PageImpl<>(users, pageable, mongoOperations.count(query, User.class));
}

From source file:com.genentech.chemistry.tool.SDFSelectivityCalculator.java

private void run(String inFile) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the SD file.

    OEMolBase mol = new OEGraphMol();
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;/*  w ww.ja  v  a  2  s .  c om*/
        if (readInput(mol)) {
            calculate();

            if (outputMode == OutputMode.SEPARATE) {
                oechem.OESetSDData(mol, selectivityOPTag, selectivityOP);
                oechem.OESetSDData(mol, selectivityTag, selectivity);
            } else {
                oechem.OESetSDData(mol, selectivityTag, selectivityOP + selectivity);
                if (outputMode == OutputMode.COMBINE_OP)
                    oechem.OESetSDData(mol, selectivityOPTag, selectivityOP);
            }
        } else {
            if (messageText != null && messageText.length() > 0)
                oechem.OESetSDData(mol, messageTag, messageText);
        }
        oechem.OEWriteMolecule(outputOEThread, mol);
    }

    //Output "." to show that the program is running.
    if (iCounter % 100 == 0)
        System.err.print(".");
    if (iCounter % 4000 == 0) {
        System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000);
    }
    mol.delete();
    ifs.close();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("%s: Read %d structures from %s. %d sec\n", MY_NAME, iCounter, inFile,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java

/**
 * Show the webpage that lists the last releases generated by Desktop packaging for a given project.
 * /*ww w  .j av a 2s.  c o m*/
 * @param project
 */
public void showPackages(final IProject project) {
    final List<Release> releases = Release.load(project);

    UIUtils.getDisplay().asyncExec(new Runnable() {
        // For now let's just pop open a dialog with the releases
        public void run() {
            try {
                InputStream in = FileLocator.openStream(DesktopPlugin.getDefault().getBundle(),
                        Path.fromPortableString("template.html"), false); //$NON-NLS-1$
                String html = IOUtil.read(in);

                StringBuilder builder = new StringBuilder();
                String appPage = StringUtil.EMPTY;
                String pubDate = StringUtil.EMPTY;
                if (releases != null) {
                    for (Release release : releases) {
                        String label = release.getLabel();
                        String url = release.getURL();
                        String platform = release.getPlatform();

                        builder.append("<div class=\"row even\">\n"); //$NON-NLS-1$
                        builder.append(
                                "<div class=\"platform\"><img height=\"20\" width=\"20\" src=\"http://studio-titanium.s3.amazonaws.com/") //$NON-NLS-1$
                                .append(platform).append("_small.png\"/></div>\n"); //$NON-NLS-1$
                        builder.append("<div class=\"label\">").append(label).append("</div>\n"); //$NON-NLS-1$ //$NON-NLS-2$
                        builder.append("<div class=\"link\"><a href=\"").append(url).append("\">").append(url) //$NON-NLS-1$ //$NON-NLS-2$
                                .append("</a></div>\n</div>\n"); //$NON-NLS-1$

                        appPage = release.getAppPage();
                        pubDate = release.getPubDate();
                    }
                }
                // We need to inject the releases into the list
                html = html.replaceAll(Pattern.quote("${RELEASES}"), builder.toString()); //$NON-NLS-1$
                html = html.replaceAll(Pattern.quote("${APP_PAGE}"), appPage); //$NON-NLS-1$
                html = html.replaceAll(Pattern.quote("${PUB_DATE}"), pubDate); //$NON-NLS-1$

                // if tehre are no releases, show the no links div in the webpage
                html = html.replaceAll(Pattern.quote("${DISPLAY_LINKS}"), //$NON-NLS-1$
                        (releases == null || releases.isEmpty()) ? "none" : "block"); //$NON-NLS-1$ //$NON-NLS-2$
                html = html.replaceAll(Pattern.quote("${DISPLAY_NO_LINKS}"), //$NON-NLS-1$
                        (releases == null || releases.isEmpty()) ? "block" : "none"); //$NON-NLS-1$ //$NON-NLS-2$

                File tmpFile = File.createTempFile("releases", ".html"); //$NON-NLS-1$ //$NON-NLS-2$
                FileWriter writer = new FileWriter(tmpFile);
                writer.write(html);
                writer.close();

                try {
                    PlatformUI.getWorkbench().getBrowserSupport()
                            .createBrowser(IWorkbenchBrowserSupport.AS_EDITOR, null,
                                    Messages.Packager_LastPackagedDist_Title,
                                    Messages.Packager_LastPackagedDist_ToolTip)
                            .openURL(new URL(tmpFile.toURI().toURL().toString()));
                } catch (Exception e) {
                    IdeLog.logError(DesktopPlugin.getDefault(), "Unable to open last packaged distribution", e); //$NON-NLS-1$
                }
            } catch (Exception e) {
                MessageDialog.openError(new Shell(), Messages.Packager_LinksWebpageOpenError, e.getMessage());
            }
        }
    });
}

From source file:com.bazaarvoice.dropwizard.caching.CacheControlConfigurationItem.java

private static Predicate<String> groupNameMatcher(String name) {
    if (name.equals("*")) {
        return Predicates.alwaysTrue();
    }/* w w  w .j  a  va  2  s.  c  o  m*/

    return regexMatcher(Pattern.compile("" + "^" + Joiner.on(".*")
            .join(FluentIterable.from(Splitter.on('*').split(name)).transform(new Function<String, Object>() {
                public Object apply(String input) {
                    return input.length() == 0 ? input : Pattern.quote(input);
                }
            })) + "$", Pattern.CASE_INSENSITIVE));
}

From source file:com.bluexml.side.Integration.eclipse.branding.enterprise.actions.ModelMigrationHelper.java

public void updateProject(final IProject source, IProject target, String libraryId, boolean makeCopy,
        IProgressMonitor monitor2) throws Exception {
    System.out.println("ModelMigrationHelper.updateProject() source :" + source.getName());
    System.out.println("ModelMigrationHelper.updateProject() target :" + target.getName());
    List<File> models = getModels(source);
    List<File> diagrams = getDiagrams(source);
    List<File> applicationModels = getApplicationModels(source);

    List<File> mavenModules = getMavenModules(source);

    List<File> modelsTarget = getModels(target);

    //      System.out.println("ModelMigrationHelper.updateProject() models :" + models.size());
    //      System.out.println("ModelMigrationHelper.updateProject() diagrams :" + diagrams.size());
    //      System.out.println("ModelMigrationHelper.updateProject() applicationModels :" + applicationModels.size());
    //      System.out.println("ModelMigrationHelper.updateProject() mavenModules :" + mavenModules.size());
    //      System.out.println("ModelMigrationHelper.updateProject() targetModels :" + modelsTarget.size());

    monitor2.beginTask("updating project",
            models.size() + applicationModels.size() + mavenModules.size() + diagrams.size());
    // System.out.println("ModelMigrationHelper.updateProject() models to update :" + models.size());
    monitor2.subTask("models references");
    for (File file : models) {
        if (monitor2.isCanceled()) {
            return;
        }//from w  w  w.  j a  va2 s.c o  m
        updateModel(file, modelsTarget, monitor2);
        monitor2.worked(1);
    }

    monitor2.subTask("diagrams references");
    for (File file : diagrams) {
        if (monitor2.isCanceled()) {
            return;
        }
        updateModel(file, modelsTarget, monitor2);
        monitor2.worked(1);
    }

    monitor2.subTask("application model");
    for (File file : applicationModels) {
        if (monitor2.isCanceled()) {
            return;
        }
        if (makeCopy) {
            updateApplicationModel(file, libraryId, source);
        } else {
            updateApplicationModel(file, libraryId, null);
        }
        AntFileGeneratorAction.generate(IFileHelper.getIFile(file));
        monitor2.worked(1);
    }

    if (makeCopy) {
        // check update project configuration
        SIDEBuilderConfiguration conf = new SIDEBuilderConfiguration(source);
        conf.load();
        String applicationRessourcePath = conf.getApplicationRessourcePath();
        String match = "(" + Pattern.quote("${workspace_loc:/") + ")" + "([^/]*)" + "(" + Pattern.quote("/")
                + ".*" + Pattern.quote("}") + ")";
        if (applicationRessourcePath.matches(match)) {
            Pattern p = Pattern.compile(match);
            Matcher matcher = p.matcher(applicationRessourcePath);
            matcher.find();
            String group1 = matcher.group(1);
            String group3 = matcher.group(3);
            String replace = group1 + source.getName() + group3;
            conf.setApplicationRessourcePath(replace);
            conf.reload();
            conf.persist();
        } else {

        }
    }

    monitor2.subTask("maven modules");
    ModelLibrary modellib = new ModelLibrary(libraryId);
    for (File file : mavenModules) {
        if (!monitor2.isCanceled()) {
            return;
        }
        String newVersion = modellib.getMavenFrameworkVersion();
        String newClassifier = modellib.getMavenFrameworkClassifier();

        String[] groupIds = modellib.getMavenFrameworkGroup().split(",");
        if (StringUtils.trimToNull(newClassifier) != null && StringUtils.trimToNull(newVersion) != null
                && StringUtils.trimToNull(libraryId) != null) {
            PomMigrationHelper.updateMavenPom(file, groupIds, newVersion, newClassifier);
        }
    }
}

From source file:com.bodybuilding.turbine.servlet.ClusterListServlet.java

/**
 * Returns Hystrix Dashboard URL/* w w  w .j av  a2  s  .c  o  m*/
 * @param sc ServletContext
 * @param request HttpServletRequest for building full URL
 * @return
 */
private Optional<String> getDashboardUrl(ServletContext sc, HttpServletRequest request) {
    String dashboardUrl = DASHBOARD_URL.get();
    if (dashboardUrl == null) {
        dashboardUrl = sc.getInitParameter("hystrix.dashboard.url");
    }

    if (dashboardUrl == null) {
        dashboardUrl = "/monitor/monitor.html?stream=";
    }

    if (!dashboardUrl.startsWith("http://") && !dashboardUrl.startsWith("https://")) {
        if (!dashboardUrl.startsWith("/")) {
            dashboardUrl = "/" + dashboardUrl;
        }
        dashboardUrl = request.getRequestURL().toString().replaceFirst(Pattern.quote(request.getServletPath()),
                dashboardUrl);
    }
    return Optional.ofNullable(dashboardUrl);
}

From source file:com.kixeye.chassis.transport.websocket.WebSocketTransportConfiguration.java

@Bean(initMethod = "start", destroyMethod = "stop")
@Order(0)/*from   w  w  w .  ja  va 2  s.  c o  m*/
public Server webSocketServer(@Value("${websocket.enabled:false}") boolean websocketEnabled,
        @Value("${websocket.hostname:}") String websocketHostname,
        @Value("${websocket.port:-1}") int websocketPort,

        @Value("${secureWebsocket.enabled:false}") boolean secureWebsocketEnabled,
        @Value("${secureWebsocket.hostname:}") String secureWebsocketHostname,
        @Value("${secureWebsocket.port:-1}") int secureWebsocketPort,
        @Value("${secureWebsocket.selfSigned:false}") boolean selfSigned,
        @Value("${secureWebsocket.mutualSsl:false}") boolean mutualSsl,

        @Value("${secureWebsocket.keyStorePath:}") String keyStorePath,
        @Value("${secureWebsocket.keyStoreData:}") String keyStoreData,
        @Value("${secureWebsocket.keyStorePassword:}") String keyStorePassword,
        @Value("${secureWebsocket.keyManagerPassword:}") String keyManagerPassword,

        @Value("${secureWebsocket.trustStorePath:}") String trustStorePath,
        @Value("${secureWebsocket.trustStoreData:}") String trustStoreData,
        @Value("${secureWebsocket.trustStorePassword:}") String trustStorePassword,

        @Value("${securewebsocket.excludedCipherSuites:}") String[] excludedCipherSuites) throws Exception {
    // set up servlets
    ServletContextHandler context = new ServletContextHandler(
            ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    for (final MessageSerDe serDe : serDes) {
        // create the websocket creator
        final WebSocketCreator webSocketCreator = new WebSocketCreator() {
            public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
                // this will have spring construct a new one for every session
                ActionInvokingWebSocket webSocket = forwardingWebSocket();
                webSocket.setSerDe(serDe);
                webSocket.setUpgradeRequest(req);
                webSocket.setUpgradeResponse(resp);

                return webSocket;
            }
        };

        // configure the websocket servlet
        ServletHolder webSocketServlet = new ServletHolder(new WebSocketServlet() {
            private static final long serialVersionUID = -3022799271546369505L;

            @Override
            public void configure(WebSocketServletFactory factory) {
                factory.setCreator(webSocketCreator);
            }
        });

        Map<String, String> webSocketProperties = new HashMap<>();
        AbstractConfiguration config = ConfigurationManager.getConfigInstance();
        Iterator<String> webSocketPropertyKeys = config.getKeys("websocket");
        while (webSocketPropertyKeys.hasNext()) {
            String key = webSocketPropertyKeys.next();

            webSocketProperties.put(key.replaceFirst(Pattern.quote("websocket."), ""), config.getString(key));
        }

        webSocketServlet.setInitParameters(webSocketProperties);

        context.addServlet(webSocketServlet, "/" + serDe.getMessageFormatName() + "/*");
    }

    // create the server
    Server server;
    if (metricRegistry == null || !monitorThreadpool) {
        server = new Server();

        server.setHandler(context);
    } else {
        server = new Server(new InstrumentedQueuedThreadPool(metricRegistry));

        InstrumentedHandler instrumented = new InstrumentedHandler(metricRegistry);
        instrumented.setHandler(context);

        server.setHandler(instrumented);
    }

    // set up connectors
    if (websocketEnabled) {
        InetSocketAddress address = StringUtils.isBlank(websocketHostname)
                ? new InetSocketAddress(websocketPort)
                : new InetSocketAddress(websocketHostname, websocketPort);

        JettyConnectorRegistry.registerHttpConnector(server, address);
    }

    if (secureWebsocketEnabled) {
        InetSocketAddress address = StringUtils.isBlank(secureWebsocketHostname)
                ? new InetSocketAddress(secureWebsocketPort)
                : new InetSocketAddress(secureWebsocketHostname, secureWebsocketPort);

        JettyConnectorRegistry.registerHttpsConnector(server, address, selfSigned, mutualSsl, keyStorePath,
                keyStoreData, keyStorePassword, keyManagerPassword, trustStorePath, trustStoreData,
                trustStorePassword, excludedCipherSuites);
    }

    return server;
}