Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

In this page you can find the example usage for java.lang StringBuilder delete.

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public long searchCount(T condition) {
    StringBuilder qString = new StringBuilder(
            "select count(model) from " + entityClass.getSimpleName() + " model");
    StringBuilder qWhere = new StringBuilder(" where ");
    StringBuilder qCondition = new StringBuilder();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityClass);
    for (int i = 0, count = propertyDescriptors.length; i < count; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        Class<?> type = propertyDescriptor.getPropertyType();
        String value = null;/*from w w  w.  j a  va  2s  . c o m*/
        try {
            value = BeanUtils.getProperty(condition, name);
        } catch (Exception e) {
            // ?
            continue;
        }
        if (value == null || name.equals("class")) {
            continue;
        }
        if ("java.lang.String".equals(type.getName())) {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append(" like ");
            qCondition.append("'%");
            qCondition.append(value);
            qCondition.append("%'");
        } else {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append("=");
            qCondition.append(value);
        }
        qCondition.append(" and ");
    }
    if (qCondition.length() != 0) {
        qString.append(qWhere).append(qCondition);
        if (qCondition.toString().endsWith(" and ")) {
            qString.delete(qString.length() - " and ".length(), qString.length());
        }
    }
    Query query = em.createQuery(qString.toString());
    return (Long) query.getSingleResult();
}

From source file:edu.wisc.jmeter.MonitorListener.java

/**
 * Builds a String of messages from the errors that occured on the request.
 *//*from   www.ja v a  2  s. co  m*/
private String getErrorMessages(SampleResult sampleResult) {
    final StringBuilder failureMessage = new StringBuilder();

    if (!sampleResult.getResponseCode().equals("200")) {
        failureMessage.append("Response code was '");
        failureMessage.append(sampleResult.getResponseCode());
        failureMessage.append("' - '");
        failureMessage.append(sampleResult.getResponseMessage());
        failureMessage.append("', ");
    } else {
        final AssertionResult[] assertionResults = sampleResult.getAssertionResults();
        for (final AssertionResult assertionResult : assertionResults) {
            if (assertionResult.isError() || assertionResult.isFailure()) {
                failureMessage.append("Assertion ");
                if (assertionResult.isError()) {
                    failureMessage.append("error");
                } else {
                    failureMessage.append("failure");
                }
                failureMessage.append(": '");

                failureMessage.append(assertionResult.getFailureMessage());
                failureMessage.append("', ");
            }
        }
    }

    //Remove the trailing , if the string is long enough
    int messageLength = failureMessage.length();
    if (messageLength > 2) {
        failureMessage.delete(messageLength - 2, messageLength);
    }

    return failureMessage.toString();
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * patch shebang on extracted files.//from ww w.  j a  v a 2s.c  om
 * simply replace standard '/usr/bin/env' with busybox one
 * @throws IOException if cannot execute shell commands
 * @throws InterruptedException if current thread get interrupted
 * @throws RuntimeException if something goes wrong
 * @throws java.util.concurrent.CancellationException if user cancelled this task
 */
private void patchShebang() throws IOException, InterruptedException, RuntimeException, CancellationException {

    if (mCurrentTask.outputDir == null)
        return;

    if (mCurrentTask.executableOutputDir == null)
        throw new IOException("output directory does not allow executable contents.");

    final StringBuilder envPath = new StringBuilder();

    mBuilder.setContentTitle(getString(R.string.patching_shebang)).setContentText("").setContentInfo("")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(100, 0, true);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    if (Shell.exec("which env", new Shell.OutputReceiver() {
        @Override
        public void onStart(String command) {
        }

        @Override
        public void onNewLine(String line) {
            if (line.length() > 0) {
                envPath.delete(0, envPath.length());
                envPath.append(line);
            }
        }

        @Override
        public void onEnd(int exitCode) {
        }
    }) != 0)
        throw new RuntimeException("cannot find 'env' executable");

    Logger.debug("envPath: " + envPath);

    Thread shell = Shell
            .async(String.format("sed -i '1s,^#!/usr/bin/env,#!%s,' $(find '%s' -type f -perm +111 )",
                    envPath.toString(), mCurrentTask.executableOutputDir), mErrorReceiver);

    if (execShell(shell, "cancelled while changing shebangs") != 0)
        throw new RuntimeException("cannot change shebang");
}

From source file:gtu._work.ui.SvnLastestCommitInfoUI.java

private void initGUI() {
    try {/*from   w  ww.jav a 2 s.  c om*/
        BorderLayout thisLayout = new BorderLayout();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(thisLayout);
        this.setFocusable(false);
        this.setTitle("SVN lastest commit wather");
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("svn dir", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        TableModel svnTableModel = new DefaultTableModel();
                        svnTable = new JTable();
                        jScrollPane1.setViewportView(svnTable);
                        svnTable.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                try {
                                    if (evt.getButton() == 3) {
                                        final List<File> list = new ArrayList<File>();
                                        SvnFile svnFile = null;
                                        final StringBuilder sb = new StringBuilder();
                                        for (int row : svnTable.getSelectedRows()) {
                                            svnFile = (SvnFile) svnTable.getModel().getValueAt(
                                                    svnTable.getRowSorter().convertRowIndexToModel(row),
                                                    SvnTableColumn.SVN_FILE.pos);
                                            list.add(svnFile.file);
                                            sb.append(svnFile.file.getName() + ",");
                                        }
                                        if (sb.length() > 200) {
                                            sb.delete(200, sb.length() - 1);
                                        }
                                        JMenuItem copySelectedMeun = new JMenuItem();
                                        copySelectedMeun.setText("copy selected file : " + list.size());
                                        copySelectedMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                for (File f : list) {
                                                                    try {
                                                                        FileUtil.copyFile(f, new File(copyToDir,
                                                                                f.getName()));
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_" + hashCode()).start();
                                            }
                                        });

                                        JMenuItem copySelectedOringTreeMeun = new JMenuItem();
                                        copySelectedOringTreeMeun
                                                .setText("copy selected file (orign tree): " + list.size());
                                        copySelectedOringTreeMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                File srcBaseDir = FileUtil
                                                                        .exportReceiveBaseDir(list);
                                                                int cutLength = 0;
                                                                if (srcBaseDir != null) {
                                                                    cutLength = srcBaseDir.getAbsolutePath()
                                                                            .length();
                                                                }

                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                File newFile = null;
                                                                for (File f : list) {
                                                                    try {
                                                                        newFile = new File(copyToDir + "/"
                                                                                + f.getAbsolutePath()
                                                                                        .substring(cutLength),
                                                                                f.getName());
                                                                        newFile.getParentFile().mkdirs();
                                                                        FileUtil.copyFile(f, newFile);
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_orignTree_" + hashCode()).start();
                                            }
                                        });

                                        JPopupMenuUtil.newInstance(svnTable).applyEvent(evt)
                                                .addJMenuItem(copySelectedMeun, copySelectedOringTreeMeun)
                                                .show();
                                    }

                                    if (!JMouseEventUtil.buttonLeftClick(2, evt)) {
                                        return;
                                    }
                                    int row = JTableUtil.newInstance(svnTable).getSelectedRow();
                                    SvnFile svnFile = (SvnFile) svnTable.getModel().getValueAt(row,
                                            SvnTableColumn.SVN_FILE.pos);
                                    String command = String.format("cmd /c call \"%s\"", svnFile.file);
                                    System.out.println(command);
                                    try {
                                        Runtime.getRuntime().exec(command);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                        svnTable.setModel(svnTableModel);
                        JTableUtil.defaultSetting(svnTable);
                    }
                }
                {
                    jPanel3 = new JPanel();
                    jPanel1.add(jPanel3, BorderLayout.NORTH);
                    jPanel3.setPreferredSize(new java.awt.Dimension(379, 35));
                    {
                        filterText = new JTextField();
                        jPanel3.add(filterText);
                        filterText.setPreferredSize(new java.awt.Dimension(258, 24));
                        filterText.getDocument()
                                .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {
                                    public void process(DocumentEvent event) {
                                        try {
                                            String scanText = JCommonUtil.getDocumentText(event);
                                            reloadSvnTable(scanText, _defaultScanProcess);
                                        } catch (Exception ex) {
                                            JCommonUtil.handleException(ex);
                                        }
                                    }
                                }));
                    }
                    {
                        choiceSvnDir = new JButton();
                        jPanel3.add(choiceSvnDir);
                        choiceSvnDir.setText("choice svn dir");
                        choiceSvnDir.setPreferredSize(new java.awt.Dimension(154, 24));
                        choiceSvnDir.addActionListener(new ActionListener() {

                            Pattern svnOutputPattern = Pattern
                                    .compile("\\s*(\\d*)\\s+(\\d+)\\s+(\\w+)\\s+([\\S]+)");

                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    System.out.println("choiceSvnDir.actionPerformed, event=" + evt);
                                    final File svnDir = JFileChooserUtil.newInstance().selectDirectoryOnly()
                                            .showOpenDialog().getApproveSelectedFile();
                                    if (svnDir == null) {
                                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                                .showMessageDialog("dir is not correct!", "ERROR");
                                        return;
                                    }
                                    Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
                                            new Runnable() {
                                                public void run() {
                                                    long startTime = System.currentTimeMillis();
                                                    String command = String
                                                            .format("cmd /c svn status -v \"%s\"", svnDir);
                                                    Matcher matcher = null;
                                                    try {
                                                        long projectLastestVersion = 0;
                                                        SvnFile svnFile = null;
                                                        Process process = Runtime.getRuntime().exec(command);
                                                        BufferedReader reader = new BufferedReader(
                                                                new InputStreamReader(process.getInputStream(),
                                                                        "BIG5"));
                                                        for (String line = null; (line = reader
                                                                .readLine()) != null;) {
                                                            matcher = svnOutputPattern.matcher(line);
                                                            if (matcher.find()) {
                                                                try {
                                                                    if (StringUtils
                                                                            .isNotBlank(matcher.group(1))) {
                                                                        projectLastestVersion = Math.max(
                                                                                projectLastestVersion,
                                                                                Long.parseLong(
                                                                                        matcher.group(1)));
                                                                    }
                                                                    svnFile = new SvnFile();
                                                                    svnFile.lastestVersion = Long
                                                                            .parseLong(matcher.group(2));
                                                                    svnFile.author = matcher.group(3);
                                                                    svnFile.filePath = matcher.group(4);
                                                                    svnFile.file = new File(svnFile.filePath);
                                                                    svnFile.fileName = svnFile.file.getName();
                                                                    svnFileSet.add(svnFile);
                                                                    authorSet.add(svnFile.author);
                                                                    String extension = null;
                                                                    if (svnFile.file.isFile()
                                                                            && (extension = getExtension(
                                                                                    svnFile.fileName)) != null) {
                                                                        fileExtenstionSet.add(extension);
                                                                    }
                                                                } catch (Exception ex) {
                                                                    ex.printStackTrace();
                                                                }
                                                            } else {
                                                                System.out.println("ignore : " + line);
                                                            }
                                                        }
                                                        reader.close();
                                                        lastestVersion = projectLastestVersion;
                                                        projectName = svnDir.getName();
                                                        resetUiAndShowMessage(startTime, projectName,
                                                                projectLastestVersion);
                                                    } catch (IOException e) {
                                                        JCommonUtil.handleException(e);
                                                    }
                                                }
                                            }, "loadSvnLastest_" + this.hashCode());
                                    thread.setDaemon(true);
                                    thread.start();
                                    setTitle("sweeping...");
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }

                            String getExtension(String name) {
                                int pos = -1;
                                if ((pos = name.lastIndexOf(".")) != -1) {
                                    return name.substring(pos).toLowerCase();
                                }
                                return null;
                            }
                        });
                    }
                    {
                        jLabel1 = new JLabel();
                        jPanel3.add(jLabel1);
                        jLabel1.setText("match :");
                        jLabel1.setPreferredSize(new java.awt.Dimension(56, 22));
                    }
                    {
                        matchCount = new JLabel();
                        jPanel3.add(matchCount);
                        matchCount.setPreferredSize(new java.awt.Dimension(82, 22));
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                FlowLayout jPanel2Layout = new FlowLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("config", null, jPanel2, null);
                {
                    DefaultComboBoxModel authorComboBoxModel = new DefaultComboBoxModel();
                    authorComboBox = new JComboBox();
                    jPanel2.add(authorComboBox);
                    authorComboBox.setModel(authorComboBoxModel);
                    authorComboBox.setPreferredSize(new java.awt.Dimension(260, 24));
                    authorComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                Object author = authorComboBox.getSelectedItem();
                                if (author instanceof Map.Entry) {
                                    Map.Entry<?, ?> entry = (Map.Entry<?, ?>) author;
                                    reloadSvnTable((String) entry.getKey(), _authorScanProcess);
                                } else {
                                    reloadSvnTable((String) author, _authorScanProcess);
                                }
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    ComboBoxModel jComboBox1Model = new DefaultComboBoxModel();
                    fileExtensionComboBox = new JComboBox();
                    jPanel2.add(fileExtensionComboBox);
                    fileExtensionComboBox.setModel(jComboBox1Model);
                    fileExtensionComboBox.setPreferredSize(new java.awt.Dimension(186, 24));
                    fileExtensionComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                String extension = (String) fileExtensionComboBox.getSelectedItem();
                                reloadSvnTable(extension, _fileExtensionScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    jScrollPane2 = new JScrollPane();
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(130, 200));
                    jPanel2.add(jScrollPane2);
                    {
                        DefaultListModel model = new DefaultListModel();
                        fileExtensionFilter = new JList();
                        jScrollPane2.setViewportView(fileExtensionFilter);
                        fileExtensionFilter.setModel(model);
                        fileExtensionFilter.addListSelectionListener(new ListSelectionListener() {
                            public void valueChanged(ListSelectionEvent evt) {
                                try {
                                    System.out
                                            .println(Arrays.toString(fileExtensionFilter.getSelectedValues()));
                                    String extensionStr = "";
                                    StringBuilder sb = new StringBuilder();
                                    for (Object val : fileExtensionFilter.getSelectedValues()) {
                                        sb.append(val + ",");
                                    }
                                    extensionStr = (sb.length() > 0 ? sb.deleteCharAt(sb.length() - 1) : sb)
                                            .toString();
                                    System.out.format("extensionStr = [%s]\n", extensionStr);
                                    multiExtendsionFilter.setName(extensionStr);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                }
                {
                    multiExtendsionFilter = new JButton();
                    jPanel2.add(multiExtendsionFilter);
                    multiExtendsionFilter.setText("multi extension filter");
                    multiExtendsionFilter.setPreferredSize(new java.awt.Dimension(166, 34));
                    multiExtendsionFilter.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                reloadSvnTable(multiExtendsionFilter.getName(), _fileExtensionMultiScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadAuthorReference = new JButton();
                    jPanel2.add(loadAuthorReference);
                    loadAuthorReference.setText("load author reference");
                    loadAuthorReference.setPreferredSize(new java.awt.Dimension(188, 35));
                    loadAuthorReference.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly().showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                authorProps.load(new FileInputStream(file));
                                reloadAuthorComboBox();
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    saveCurrentData = new JButton();
                    jPanel2.add(saveCurrentData);
                    saveCurrentData.setText("save current data");
                    saveCurrentData.setPreferredSize(new java.awt.Dimension(166, 34));
                    saveCurrentData.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File saveDataConfig = new File(jarExistLocation, getSaveCurrentDataFileName());
                                ObjectOutputStream writer = new ObjectOutputStream(
                                        new FileOutputStream(saveDataConfig));
                                writer.writeObject(projectName);
                                writer.writeObject(authorSet);
                                writer.writeObject(fileExtenstionSet);
                                writer.writeObject(svnFileSet);
                                writer.writeObject(authorProps);
                                writer.writeObject(lastestVersion);
                                writer.flush();
                                writer.close();

                                JOptionPaneUtil.newInstance().iconInformationMessage()
                                        .showMessageDialog("current project : " + projectName
                                                + " save completed! \n" + saveDataConfig, "SUCCESS");
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadDataFromFile = new JButton();
                    jPanel2.add(loadDataFromFile);
                    loadDataFromFile.setText("load data cfg");
                    loadDataFromFile.setPreferredSize(new java.awt.Dimension(165, 35));
                    loadDataFromFile.addActionListener(new ActionListener() {
                        @SuppressWarnings("unchecked")
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly()
                                        .addAcceptFile(".cfg", ".cfg").showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                long startTime = System.currentTimeMillis();
                                ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
                                projectName = (String) input.readObject();
                                authorSet = (Set<String>) input.readObject();
                                fileExtenstionSet = (Set<String>) input.readObject();
                                svnFileSet = (Set<SvnFile>) input.readObject();
                                authorProps = (Properties) input.readObject();
                                lastestVersion = (Long) input.readObject();
                                input.close();

                                resetUiAndShowMessage(startTime, projectName, lastestVersion);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
            }
        }
        pack();
        this.setSize(726, 459);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.gael.dhus.olingo.v1.Processor.java

private URI makeLink(boolean remove_last_segment) throws ODataException {
    try {/*from   w  w w  .ja va  2  s.  c o  m*/
        URIBuilder ub = new URIBuilder(ServiceFactory.EXTERNAL_URL);
        StringBuilder sb = new StringBuilder();

        String prefix = ub.getPath();
        String path = getContext().getPathInfo().getRequestUri().getPath();
        if (path == null || path.isEmpty()
                || prefix != null && !prefix.isEmpty() && !path.startsWith(ub.getPath())) {
            sb.append(prefix);

            if (path != null) {
                if (prefix.endsWith("/") && path.startsWith("/")) {
                    sb.deleteCharAt(sb.length() - 1);
                }
                if (!prefix.endsWith("/") && !path.startsWith("/")) {
                    sb.append('/');
                }
            }
        }
        sb.append(path);

        if (remove_last_segment) {
            // Removes the last segment.
            int lio = sb.lastIndexOf("/");
            while (lio != -1 && lio == sb.length() - 1) {
                sb.deleteCharAt(lio);
                lio = sb.lastIndexOf("/");
            }
            if (lio != -1) {
                sb.delete(lio + 1, sb.length());
            }

            // Removes the `$links` segment.
            lio = sb.lastIndexOf("$links/");
            if (lio != -1) {
                sb.delete(lio, lio + 7);
            }
        } else if (!sb.toString().endsWith("/") && !sb.toString().endsWith("\\")) {
            sb.append("/");
        }
        ub.setPath(sb.toString());
        return ub.build();
    } catch (NullPointerException | URISyntaxException e) {
        throw new ODataException(e);
    }
}

From source file:io.anserini.doc.DataModel.java

public String generateRankingCommand(String collection) {
    Map<String, Object> config = this.collections.get(collection);
    StringBuilder builder = new StringBuilder();
    ObjectMapper oMapper = new ObjectMapper();
    List models = oMapper.convertValue((List) safeGet(config, "models"), List.class);
    List topics = oMapper.convertValue((List) safeGet(config, "topics"), List.class);
    for (Object modelObj : models) {
        Model model = oMapper.convertValue(modelObj, Model.class);
        for (Object topicObj : topics) {
            Topic topic = oMapper.convertValue(topicObj, Topic.class);
            builder.append("nohup ");
            builder.append(safeGet(config, "search_command"));
            builder.append(" ").append("-topicreader").append(" ").append(safeGet(config, "topic_reader"));
            builder.append(" ").append("-index").append(" ")
                    .append("lucene-index." + safeGet(config, "name") + ".pos+docvectors");
            builder.append(" ").append("-topic").append(" ")
                    .append(Paths.get((String) safeGet(config, "topic_root"), topic.getPath()).toString());
            builder.append(" ").append("-output").append(" ")
                    .append("run." + safeGet(config, "name") + "." + model.getName() + "." + topic.getPath());
            List modelParams = oMapper.convertValue(model.getParams(), List.class);
            if (modelParams != null) {
                for (Object option : modelParams) {
                    builder.append(" ").append(option);
                }// ww  w . java 2 s .  c o  m
            }
            builder.append(" &"); // nohup
            builder.append("\n");
        }
        builder.append("\n");
    }
    builder.delete(builder.lastIndexOf("\n"), builder.length());

    return builder.toString();
}

From source file:com.vmware.bdd.cli.commands.ClusterCommands.java

private String getValidateWarningMsg(List<String> failureNames, String warningMsg) {
    StringBuilder warningMsgBuff = new StringBuilder();
    if (failureNames != null && !failureNames.isEmpty()) {
        warningMsgBuff.append("Warning: ");
        for (String failureName : failureNames) {
            warningMsgBuff.append(failureName).append(", ");
        }/*from  w w w. j  a  v a  2 s. c o m*/
        warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length());
        if (failureNames.size() > 1) {
            warningMsgBuff.append(" are ");
        } else {
            warningMsgBuff.append(" is ");
        }
        warningMsgBuff.append(warningMsg);
    }
    return warningMsgBuff.toString();
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

/**
 * See <a href="https://issues.alfresco.com/jira/browse/ALF-12638">ALF-12638</a>
 *//*  w ww.  ja  v  a 2 s  . c  o  m*/
public void testAuditFailedNodeAccess() throws Exception {
    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);
    params.setApplicationName(APPLICATION_ALF12638_TEST);

    // Load in the config for this specific test: alfresco-audit-test-authenticationservice.xml
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-alf-12638.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    // There should be a log entry for the application
    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_ALF12638_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    try {
        nodeService.getRootNode(new StoreRef("system://system"));
        fail("Should not be allowed to get 'system://system'");
    } catch (AccessDeniedException e) {
        // Expected
    }
    // Try this for a while until we get a result
    boolean success = false;
    for (int i = 0; i < 30; i++) {
        queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
        if (results.size() > 1) {
            logger.debug(sb.toString());
            success = true;
            break;
        }
        synchronized (this) {
            try {
                this.wait(1000L);
            } catch (InterruptedException e) {
            }
        }
    }
    assertTrue("There should be exactly one audit entry for the API test", success);
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

/**
  * See <a href="https://issues.alfresco.com/jira/browse/MNT-10767">MNT-10767</a>
  */// www  .  ja  v  a 2  s  .c  o  m
public void testAuditSubordinateCall() throws Exception {
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);
    params.setApplicationName(APPLICATION_MNT10767_TEST);

    // Load in the config for this specific test: alfresco-audit-test-mnt-10767
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-10767.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();
    // There should be a log entry for the application
    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_MNT10767_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    PolicyComponent policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    policyComponent.bindClassBehaviour(OnCreateNodePolicy.QNAME, ContentModel.TYPE_FOLDER,
            new JavaBehaviour(this, "onCreateFolderMNT10767"));

    NodeRef workingRootNodeRef = null;
    try {
        workingRootNodeRef = nodeService
                .createNode(nodeRef, ContentModel.ASSOC_CHILDREN,
                        QName.createQName(NamespaceService.ALFRESCO_URI,
                                "working_root" + System.currentTimeMillis()),
                        ContentModel.TYPE_FOLDER)
                .getChildRef();

        // Try this for a while until we get a result
        boolean success = false;
        for (int i = 0; i < 30; i++) {
            queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
            if (results.size() > 1) {
                logger.debug(sb.toString());
                success = true;
                break;
            }
            synchronized (this) {
                try {
                    this.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        assertTrue("There should be audit entry for the API test", success);
    } finally {
        if (workingRootNodeRef != null) {
            nodeService.deleteNode(workingRootNodeRef);
        }
    }
}

From source file:jenkins.branch.NameMangler.java

public static String apply(String name) {
    if (name.length() <= MAX_SAFE_LENGTH) {
        boolean unsafe = false;
        boolean first = true;
        for (char c : name.toCharArray()) {
            if (first) {
                if (c == '-') {
                    // no leading dash
                    unsafe = true;/*from  www .j a  v a2 s . c  o m*/
                    break;
                }
                first = false;
            }
            if (!isSafe(c)) {
                unsafe = true;
                break;
            }
        }
        // See https://msdn.microsoft.com/en-us/library/aa365247 we need to consistently reserve names across all OS
        if (!unsafe) {
            // we know it is only US-ASCII if we got to here
            switch (name.toLowerCase(Locale.ENGLISH)) {
            case ".":
            case "..":
            case "con":
            case "prn":
            case "aux":
            case "nul":
            case "com1":
            case "com2":
            case "com3":
            case "com4":
            case "com5":
            case "com6":
            case "com7":
            case "com8":
            case "com9":
            case "lpt1":
            case "lpt2":
            case "lpt3":
            case "lpt4":
            case "lpt5":
            case "lpt6":
            case "lpt7":
            case "lpt8":
            case "lpt9":
                unsafe = true;
                break;
            default:
                if (name.endsWith(".")) {
                    unsafe = true;
                }
                break;
            }
        }
        if (!unsafe) {
            return name;
        }
    }
    StringBuilder buf = new StringBuilder(name.length() + 16);
    for (char c : name.toCharArray()) {
        if (isSafe(c)) {
            buf.append(c);
        } else if (c == '/' || c == '\\' || c == ' ' || c == '.' || c == '_') {
            if (buf.length() == 0) {
                buf.append("0-");
            } else {
                buf.append('-');
            }
        } else if (c <= 0xff) {
            if (buf.length() == 0) {
                buf.append("0_");
            } else {
                buf.append('_');
            }
            buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0'));
        } else {
            if (buf.length() == 0) {
                buf.append("0_");
            } else {
                buf.append('_');
            }
            buf.append(StringUtils.leftPad(Integer.toHexString(((c & 0xffff) >> 8) & 0xff), 2, '0'));
            buf.append('_');
            buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0'));
        }
    }
    // use the digest of the original name
    String digest;
    try {
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] bytes = sha.digest(name.getBytes(StandardCharsets.UTF_8));
        int bits = 0;
        int data = 0;
        StringBuffer dd = new StringBuffer(32);
        for (byte b : bytes) {
            while (bits >= 5) {
                dd.append(toDigit(data & 0x1f));
                bits -= 5;
                data = data >> 5;
            }
            data = data | ((b & 0xff) << bits);
            bits += 8;
        }
        digest = dd.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA-1 not installed", e); // impossible
    }
    if (buf.length() <= MAX_SAFE_LENGTH - MIN_HASH_LENGTH - 1) {
        // we have room to add the min hash
        buf.append('.');
        buf.append(StringUtils.right(digest, MIN_HASH_LENGTH));
        return buf.toString();
    }
    // buf now holds the mangled string, we will now try and rip the middle out to put in some of the digest
    int overage = buf.length() - MAX_SAFE_LENGTH;
    String hash;
    if (overage <= MIN_HASH_LENGTH) {
        hash = "." + StringUtils.right(digest, MIN_HASH_LENGTH) + ".";
    } else if (overage > MAX_HASH_LENGTH) {
        hash = "." + StringUtils.right(digest, MAX_HASH_LENGTH) + ".";
    } else {
        hash = "." + StringUtils.right(digest, overage) + ".";
    }
    int start = (MAX_SAFE_LENGTH - hash.length()) / 2;
    buf.delete(start, start + hash.length() + overage);
    buf.insert(start, hash);
    return buf.toString();
}