Search in sources :

Example 1 with MapFormat

use of org.openide.util.MapFormat in project netbeans-rcp-lite by outersky.

the class MapFormatTest method testExectLineWithTheProblemFromFormatIssue67238.

public void testExectLineWithTheProblemFromFormatIssue67238() {
    String s = "/*___________________________________________________________________________*/";
    HashMap args = new HashMap();
    args.put("NAME", "Jaroslav");
    MapFormat f = new MapFormat(args);
    f.setLeftBrace("__");
    f.setRightBrace("__");
    f.setExactMatch(false);
    String result = f.format(s);
    assertEquals("Should be ok: " + result, s, result);
}
Also used : HashMap(java.util.HashMap) MapFormat(org.openide.util.MapFormat)

Example 2 with MapFormat

use of org.openide.util.MapFormat in project netbeans-rcp-lite by outersky.

the class MapFormatTest method testFormatIssue67238.

public void testFormatIssue67238() {
    HashMap args = new HashMap();
    args.put("NAME", "Jaroslav");
    MapFormat f = new MapFormat(args);
    f.setLeftBrace("__");
    f.setRightBrace("__");
    f.setExactMatch(false);
    String result = f.format("/*_____________________*/\n/*__NAME__*/");
    assertEquals("Should be ok: " + result, "/*_____________________*/\n/*Jaroslav*/", result);
}
Also used : HashMap(java.util.HashMap) MapFormat(org.openide.util.MapFormat)

Example 3 with MapFormat

use of org.openide.util.MapFormat in project netbeans-rcp-lite by outersky.

the class FileBuilder method createFromTemplate.

/**
 * Creates a new file based on the template. This convenience method is intended for easier
 * migration of clients using DataLoader templating API before {@link FileBuilder} introduction.
 * The method will collect parameters
 * tied to the template using registered {@link CreateFromTemplateAttributes} providers,
 * and will try to locate a willing {@link CreateFromTemplateHandler} that will create
 * the target file. If no such handler exists, and the {@code defaultCopy} parameter is true,
 * the file contents is just copied to the target location.
 * <p>
 * If the {@code name} parameter is null, the function attempts to compute a suitable name
 * from the file.
 * <p>
 * The default copy algorithm uses the supplied {@link Mode#FORMAT} to
 * process tokens.
 * <p>
 * If the passed {@code name} is {@code null}, the implementation will pick a free name based on
 * the template's own name (see {@link FileUtil#findFreeFileName}).
 * @param f the template file
 * @param folder the target folder, must exist
 * @param name the desired name. If {@code null}, the implementation will choose the name.
 * @param attributes values to apply on the template. May be {@code null} = no values.
 * @param defaultMode the mode of operations to use
 * @return The created file, or {@code null} if no creation handler is located.
 * @throws IOException when an I/O operation fails
 */
@SuppressWarnings("AssignmentToMethodParameter")
@CheckForNull
public static FileObject createFromTemplate(@NonNull FileObject f, @NonNull FileObject folder, @NullAllowed String name, @NullAllowed Map<String, ?> attributes, Mode defaultMode) throws IOException {
    Format frm = null;
    switch(defaultMode) {
        case FORMAT:
            MapFormat mf = new MapFormat(new HashMap());
            mf.setExactMatch(false);
            mf.setLeftBrace("__");
            mf.setRightBrace("__");
            frm = mf;
            break;
        case COPY:
            frm = new Format() {

                @Override
                public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
                    toAppendTo.append(obj);
                    return toAppendTo;
                }

                @Override
                public Object parseObject(String source, ParsePosition pos) {
                    // To change body of generated methods, choose Tools | Templates.
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            };
            break;
    }
    FileBuilder fb = new FileBuilder(f, folder).name(name).withParameters(attributes).useFormat(frm).defaultMode(defaultMode);
    List<FileObject> fos = fb.build();
    if (fos == null || fos.isEmpty()) {
        return null;
    } else {
        return fos.iterator().next();
    }
}
Also used : HashMap(java.util.HashMap) FieldPosition(java.text.FieldPosition) Format(java.text.Format) MapFormat(org.openide.util.MapFormat) MapFormat(org.openide.util.MapFormat) FileObject(org.openide.filesystems.FileObject) FileObject(org.openide.filesystems.FileObject) ParsePosition(java.text.ParsePosition) CheckForNull(org.netbeans.api.annotations.common.CheckForNull)

Example 4 with MapFormat

use of org.openide.util.MapFormat in project netbeans-rcp-lite by outersky.

the class MapFormatTest method testIssue67238.

public void testIssue67238() {
    final String s = "/*___________________________________________________________________________*/";
    HashMap args = new HashMap();
    args.put("NAME", "Jaroslav");
    MapFormat f = new MapFormat(args) {

        protected Object processKey(String key) {
            fail("There is no key in \"" + s + "\", processKey() should not be called with key:" + key);
            return "not defined";
        }
    };
    f.setLeftBrace("__");
    f.setRightBrace("__");
    f.setExactMatch(false);
    f.format(s);
}
Also used : HashMap(java.util.HashMap) MapFormat(org.openide.util.MapFormat)

Example 5 with MapFormat

use of org.openide.util.MapFormat in project netbeans-rcp-lite by outersky.

the class CreateFromTemplateImpl method defaultCreate.

/**
 * Creates the file using the default algorithm - no handler is willing to participate
 * @return created file
 * @throws IOException
 */
private FileObject defaultCreate() throws IOException {
    Map<String, ?> params = desc.getParameters();
    FileBuilder.Mode defaultMode = builder.defaultMode;
    Format frm = builder.format;
    if (defaultMode != FileBuilder.Mode.COPY && frm instanceof MapFormat) {
        MapFormat mf = (MapFormat) frm;
        Map m = mf.getMap();
        Map x = null;
        for (String s : params.keySet()) {
            if (m.containsKey(s)) {
                continue;
            }
            if (x == null) {
                x = new HashMap<>(m);
            }
            x.put(s, params.get(s));
        }
        if (x != null) {
            mf.setMap(x);
        }
    }
    FileObject f = desc.getTemplate();
    String ext = desc.getTemplate().getExt();
    FileObject fo = desc.getTarget().createData(desc.getProposedName(), ext);
    boolean preformatted = false;
    Charset encoding = FileEncodingQuery.getEncoding(f);
    boolean success = false;
    FileLock lock = fo.lock();
    try (InputStream is = f.getInputStream();
        Reader reader = new InputStreamReader(is, encoding);
        BufferedReader r = new BufferedReader(reader)) {
        preformatted = desc.isPreformatted();
        encoding = FileEncodingQuery.getEncoding(fo);
        // Document doc = ScriptingCreateFromTemplateHandler.createDocument(f.getMIMEType());
        ScriptEngine en = desc.isPreformatted() ? null : ScriptingCreateFromTemplateHandler.indentEngine();
        // PENDING: originally, preformatted meant that only changed
        // lines were formatted. Now preformatted is not formatted at all
        StringWriter sw = new StringWriter();
        try (OutputStream os = fo.getOutputStream(lock);
            OutputStreamWriter w = new OutputStreamWriter(os, encoding);
            Writer iw = preformatted || en == null ? w : sw) {
            String line = null;
            String current;
            while ((current = r.readLine()) != null) {
                if (line != null) {
                    // newline between lines
                    iw.append(NEWLINE);
                }
                if (frm != null) {
                    line = frm.format(current);
                } else {
                    line = current;
                }
                iw.append(line);
            }
            iw.append(NEWLINE);
            iw.flush();
            if (en != null) {
                en.getContext().setAttribute("mimeType", f.getMIMEType(), ScriptContext.ENGINE_SCOPE);
                en.getContext().setWriter(w);
                en.eval(new StringReader(sw.toString()));
            }
        }
        // copy attributes
        // hack to overcome package-private modifier in setTemplate(fo, boolean)
        FileUtil.copyAttributes(f, fo);
        fo.setAttribute(PROP_TEMPLATE, null);
        success = true;
    } catch (IOException ex) {
        try {
            fo.delete(lock);
        } catch (IOException ex2) {
        }
        throw ex;
    } catch (ScriptException ex) {
        IOException io = ex.getCause() instanceof IOException ? (IOException) ex.getCause() : null;
        try {
            fo.delete(lock);
        } catch (IOException ex2) {
        }
        throw io == null ? new IOException(ex) : io;
    } finally {
        if (!success) {
            // try to delete the malformed file:
            fo.delete(lock);
        }
        lock.releaseLock();
    }
    return fo;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) Format(java.text.Format) MapFormat(org.openide.util.MapFormat) StringWriter(java.io.StringWriter) MapFormat(org.openide.util.MapFormat) FileLock(org.openide.filesystems.FileLock) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) FileObject(org.openide.filesystems.FileObject) HashMap(java.util.HashMap) Map(java.util.Map) OutputStreamWriter(java.io.OutputStreamWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Aggregations

HashMap (java.util.HashMap)5 MapFormat (org.openide.util.MapFormat)5 Format (java.text.Format)2 FileObject (org.openide.filesystems.FileObject)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 Charset (java.nio.charset.Charset)1 FieldPosition (java.text.FieldPosition)1 ParsePosition (java.text.ParsePosition)1 Map (java.util.Map)1 ScriptEngine (javax.script.ScriptEngine)1 ScriptException (javax.script.ScriptException)1