Java Code Examples for java.io.PrintWriter#format()

The following examples show how to use java.io.PrintWriter#format() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConceptFileWriter.java    From bluima with Apache License 2.0 10 votes vote down vote up
public static void writeConceptFile(File f, Collection<Concept> concepts,
        String msg) throws FileNotFoundException {

    PrintWriter w = new PrintWriter(f);
    w.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
    w.append("<!-- generated by ConceptFileWriter on " + nowToHuman()
            + " -->\n");
    if (msg != null && msg.length() > 0) {
        w.append("<!--  " + escape(msg) + " -->\n");
    }
    w.append("<synonym>\n");

    for (Concept c : concepts) {

        w.format("<token canonical=\"%s\" ref_id=\"%s\">\n",
                escape(c.canonical), escape(c.id));

        for (String v : c.variants) {
            w.format("  <variant base=\"%s\" />\n", escape(v));
        }
        w.append("</token>\n");
    }
    w.append("</synonym>\n");
    w.close();
}
 
Example 2
Source File: CatalogCrawler.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static boolean readAccess(Access access, DataFactory fac, PrintWriter pw) {
  Formatter log = new Formatter();
  try (NetcdfDataset ncd = fac.openDataset(access, false, null, log)) {
    if (ncd == null) {
      pw.format("  Dataset opendap fatalError=%s%n", log);
      return false;

    } else {
      pw.format("  Dataset '%s' opened as %s%n", access.getDataset().getName(), access.getService());
      return readRandom(ncd, pw);
    }
  } catch (InvalidRangeException | IOException e) {
    e.printStackTrace(pw);
    return false;
  }
}
 
Example 3
Source File: Mips.java    From decaf-mind-compiler with Apache License 2.0 6 votes vote down vote up
private String emitToString(String label, String body, String comment) {
	if (comment != null && label == null && body == null) {
		return "                                        # " + comment;
	} else {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		if (label != null) {
			if (body == null) {
				pw.format("%-40s", label + ":");
			} else {
				pw.println(label + ":");
			}
		}
		if (body != null) {
			pw.format("          %-30s", body);
		}
		if (comment != null) {
			pw.print("# " + comment);
		}
		pw.close();
		return sw.toString();
	}
}
 
Example 4
Source File: GNUStyleOptions.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void printHelp0(PrintWriter out, boolean printExtra) {
    out.format("%s%n", Main.getMsg("main.help.preopt"));
    for (OptionType type : OptionType.values()) {
        boolean typeHeadingWritten = false;

        for (Option o : recognizedOptions) {
            if (!o.type.equals(type))
                continue;
            String name = o.aliases[0].substring(1); // there must always be at least one name
            name = name.charAt(0) == '-' ? name.substring(1) : name;
            if (o.isHidden() || name.equals("h")) {
                continue;
            }
            if (o.isExtra() && !printExtra) {
                continue;
            }
            if (!typeHeadingWritten) {
                out.format("%n%s%n", Main.getMsg("main.help.opt." + type.name));
                typeHeadingWritten = true;
            }
            out.format("%s%n", Main.getMsg("main.help.opt." + type.name + "." + name));
        }
    }
    out.format("%n%s%n%n", Main.getMsg("main.help.postopt"));
}
 
Example 5
Source File: RxJava2Generator.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
private void genToXXXEr(TypeInfo streamType, String rxType, String rxName, PrintWriter writer) {
  writer.format("  public synchronized WriteStream%s<%s> to%s() {%n", rxType, genTranslatedTypeName(streamType), rxType);

  writer.format("    if (%s == null) {%n", rxName);

  if (streamType.getKind() == ClassKind.API) {
    writer.format("      Function<%s, %s> conv = %s::getDelegate;%n", genTranslatedTypeName(streamType.getRaw()), streamType.getName(), genTranslatedTypeName(streamType));

    writer.format("      %s = RxHelper.to%s(getDelegate(), conv);%n", rxName, rxType);
  } else if (streamType.isVariable()) {
    String typeVar = streamType.getSimpleName();
    writer.format("      Function<%s, %s> conv = (Function<%s, %s>) __typeArg_0.unwrap;%n", typeVar, typeVar, typeVar, typeVar);

    writer.format("      %s = RxHelper.to%s(getDelegate(), conv);%n", rxName, rxType);
  } else {
    writer.format("      %s = RxHelper.to%s(getDelegate());%n", rxName, rxType);
  }

  writer.println("    }");
  writer.format("    return %s;%n", rxName);
  writer.println("  }");
  writer.println();
}
 
Example 6
Source File: EpfFileModelWriter.java    From workspacemechanic with Eclipse Public License 1.0 6 votes vote down vote up
public static void write(EpfFileModel model, OutputStream outputStream) throws IOException {
  PrintWriter commentPrintWriter = new PrintWriter(outputStream);
  commentPrintWriter.format("# @title %s\n", model.getTitle());
  commentPrintWriter.format("# @description %s\n", model.getDescription());
  commentPrintWriter.format("# @task_type %s\n#\n", model.getTaskType().toString());
  commentPrintWriter.println(
      "# Created by the Workspace Mechanic Preference Recorder");
  commentPrintWriter.flush();

  // Use java Properties object to output key/value pairs
  
  Properties outputProperties = new Properties();
  
  outputProperties.setProperty("file_export_version", "3.0");
  
  for (Map.Entry<String, String> e : model.getPreferences().entrySet()) {
    String value = e.getValue();
    if(value == null) {
      value = "";
    }
    outputProperties.setProperty(e.getKey(), value);
  }

  outputProperties.store(outputStream, null);
}
 
Example 7
Source File: UniqueArtifactProcessor.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void streamHtmlState ( final PrintWriter writer )
{
    writer.format ( "Ensure that all artifacts with the key%s %s have the same value in <code>%s</code> by: %s.", this.cfg.getKeys ().length > 1 ? "s" : "", format ( this.cfg.getKeys () ), format ( this.cfg.getUniqueAttribute () ), format ( this.cfg.getVetoPolicy () ) );
    if ( this.cfg.isSkipMissingAttributes () )
    {
        writer.format ( " Artifacts with missing <q>artifact keys</q> will not be checked." );
    }
}
 
Example 8
Source File: ModuleAnalyzer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void printModuleDescriptor(PrintWriter out, Module module) {
    ModuleDescriptor descriptor = module.descriptor();
    out.format("%s (%s)%n", descriptor.name(), module.location());

    if (descriptor.name().equals(JAVA_BASE))
        return;

    out.println("  [Module descriptor]");
    descriptor.requires()
        .stream()
        .sorted(Comparator.comparing(ModuleDescriptor.Requires::name))
        .forEach(req -> out.format("    requires %s;%n", req));
}
 
Example 9
Source File: XMLTargetWriter.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitEnd(Map<String, String> targetTags) {
	try {
		final PrintWriter out = new PrintWriter(targetFile, "UTF-8");

		out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		final StringBuilder targetAttributes = new StringBuilder();
		for (final Entry<String, String> entry : targetTags.entrySet()) {
			if (targetAttributes.length() > 0) targetAttributes.append(" ");

			targetAttributes.append(entry.getKey());
			targetAttributes.append("=\"");
			targetAttributes.append(entry.getValue());
			targetAttributes.append("\"");
		}

		if (targetAttributes.length() > 0) {
			out.format("<target %s>%n", targetAttributes.toString());
		} else {
			out.println("<target>");
		}

		out.print(xmlBody.toString());
		out.println("</target>");

		out.close();

	} catch (final IOException e) {
		logger.error("Error writing XML target", e);
	}
}
 
Example 10
Source File: RxJavaGenerator.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
protected void genToSubscriber(TypeInfo streamType, PrintWriter writer) {
  writer.format("  private WriteStreamSubscriber<%s> subscriber;%n", genTranslatedTypeName(streamType));
  writer.println();

  writer.format("  public synchronized WriteStreamSubscriber<%s> toSubscriber() {%n", genTranslatedTypeName(streamType));

  writer.println("    if (subscriber == null) {");

  if (streamType.getKind() == ClassKind.API) {
    writer.format("      Function<%s, %s> conv = %s::getDelegate;%n", genTranslatedTypeName(streamType.getRaw()), streamType.getName(), genTranslatedTypeName(streamType));

    writer.println("      subscriber = RxHelper.toSubscriber(getDelegate(), conv);");
  } else if (streamType.isVariable()) {
    String typeVar = streamType.getSimpleName();
    writer.format("      Function<%s, %s> conv = (Function<%s, %s>) __typeArg_0.unwrap;%n", typeVar, typeVar, typeVar, typeVar);

    writer.println("      subscriber = RxHelper.toSubscriber(getDelegate(), conv);");
  } else {
    writer.println("      subscriber = RxHelper.toSubscriber(getDelegate());");
  }

  writer.println("    }");
  writer.println("    return subscriber;");
  writer.println("  }");
  writer.println();
}
 
Example 11
Source File: MergeCommand.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(CommandLine options) throws Exception {
  // Prepare arguments
  List<String> args = options.getArgList();
  List<Path> inputFiles = getInputFiles(args.subList(0, args.size() - 1));
  Path outputFile = new Path(args.get(args.size() - 1));

  // Merge schema and extraMeta
  FileMetaData mergedMeta = mergedMetadata(inputFiles);
  PrintWriter out = new PrintWriter(Main.out, true);

  // Merge data
  ParquetFileWriter writer = new ParquetFileWriter(conf,
          mergedMeta.getSchema(), outputFile, ParquetFileWriter.Mode.CREATE);
  writer.start();
  boolean tooSmallFilesMerged = false;
  for (Path input: inputFiles) {
    if (input.getFileSystem(conf).getFileStatus(input).getLen() < TOO_SMALL_FILE_THRESHOLD) {
      out.format("Warning: file %s is too small, length: %d\n",
        input,
        input.getFileSystem(conf).getFileStatus(input).getLen());
      tooSmallFilesMerged = true;
    }

    writer.appendFile(HadoopInputFile.fromPath(input, conf));
  }

  if (tooSmallFilesMerged) {
    out.println("Warning: you merged too small files. " +
      "Although the size of the merged file is bigger, it STILL contains small row groups, thus you don't have the advantage of big row groups, " +
      "which usually leads to bad query performance!");
  }
  writer.end(mergedMeta.getKeyValueMetaData());
}
 
Example 12
Source File: CLVFImportSource.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void dump(PrintWriter out, String prefix) {
	out.format("%02d:%s:%s%n",getLine(),sourceToImport,toString(prefix));
	if (children != null) {
		for (int i = 0; i < children.length; ++i) {
			SimpleNode n = (SimpleNode) children[i];
			if (n != null) {
				n.dump(out,prefix + " ");
			}
		}
	}
}
 
Example 13
Source File: HttpTrigger.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
protected String renderHtmlState ()
{
    final StringWriter sw = new StringWriter ();
    final PrintWriter pw = new PrintWriter ( sw );

    final String prefix = this.prefixService.getSitePrefix ();
    pw.format ( "Run the trigger when a <code>POST</code> request is being made to: <a href=\"%1$s\">%1$s</a>", prefix + makeAlias () );

    return sw.toString ();
}
 
Example 14
Source File: SizeCommand.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(CommandLine options) throws Exception {
  super.execute(options);

  String[] args = options.getArgs();
  String input = args[0];
  out = new PrintWriter(Main.out, true);
  inputPath = new Path(input);
  conf = new Configuration();
  inputFileStatuses = inputPath.getFileSystem(conf).globStatus(inputPath);
  long size = 0;
  for (FileStatus fs : inputFileStatuses) {
    long fileSize = 0;
    for (Footer f : ParquetFileReader.readFooters(conf, fs, false)) {
      for (BlockMetaData b : f.getParquetMetadata().getBlocks()) {
        size += (options.hasOption('u') ? b.getTotalByteSize() : b.getCompressedSize());
        fileSize += (options.hasOption('u') ? b.getTotalByteSize() : b.getCompressedSize());
      }
    }
    if (options.hasOption('d')) {
      if (options.hasOption('p')) {
        out.format("%s: %s\n", fs.getPath().getName(), getPrettySize(fileSize));
      }
      else {
        out.format("%s: %d bytes\n", fs.getPath().getName(), fileSize);
      }
    }
  }

  if (options.hasOption('p')) {
    out.format("Total Size: %s", getPrettySize(size));
  }
  else {
    out.format("Total Size: %d bytes", size);
  }
  out.println();
}
 
Example 15
Source File: PlateCompositionWriter.java    From act with GNU General Public License v3.0 5 votes vote down vote up
protected void writePlateAttributes(PrintWriter w, Plate plate) throws IOException {
  w.format(">%s\t%s\n", "name", plate.getName());
  w.format(">%s\t%s\n", "description", plate.getDescription());
  w.format(">%s\t%s\n", "barcode", plate.getBarcode());
  w.println(">schema\tplate\n");
  w.format(">%s\t%s\n", "location", plate.getLocation());
  w.format(">%s\t%s\n", "plate_type", plate.getPlateType());
  if (plate.getSolvent() != null) {
    w.format(">%s\t%s\n", "solvent", plate.getSolvent());
  }
  w.format(">%s\t%d\n", "temperature", plate.getTemperature());
  w.println();
}
 
Example 16
Source File: ColumnIndexCommand.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(CommandLine options) throws Exception {
  super.execute(options);

  String[] args = options.getArgs();
  InputFile in = HadoopInputFile.fromPath(new Path(args[0]), new Configuration());
  PrintWriter out = new PrintWriter(Main.out, true);
  String rowGroupValue = options.getOptionValue("r");
  Set<String> indexes = new HashSet<>();
  if (rowGroupValue != null) {
    indexes.addAll(Arrays.asList(rowGroupValue.split("\\s*,\\s*")));
  }
  boolean showColumnIndex = options.hasOption("i");
  boolean showOffsetIndex = options.hasOption("o");
  if (!showColumnIndex && !showOffsetIndex) {
    showColumnIndex = true;
    showOffsetIndex = true;
  }

  try (ParquetFileReader reader = ParquetFileReader.open(in)) {
    boolean firstBlock = true;
    int rowGroupIndex = 0;
    for (BlockMetaData block : reader.getFooter().getBlocks()) {
      if (!indexes.isEmpty() && !indexes.contains(Integer.toString(rowGroupIndex))) {
        ++rowGroupIndex;
        continue;
      }
      if (!firstBlock) {
        out.println();
        firstBlock = false;
      }
      out.format("row group %d:%n", rowGroupIndex);
      for (ColumnChunkMetaData column : getColumns(block, options)) {
        String path = column.getPath().toDotString();
        if (showColumnIndex) {
          out.format("column index for column %s:%n", path);
          ColumnIndex columnIndex = reader.readColumnIndex(column);
          if (columnIndex == null) {
            out.println("NONE");
          } else {
            out.println(columnIndex);
          }
        }
        if (showOffsetIndex) {
          out.format("offset index for column %s:%n", path);
          OffsetIndex offsetIndex = reader.readOffsetIndex(column);
          if (offsetIndex == null) {
            out.println("NONE");
          } else {
            out.println(offsetIndex);
          }
        }
      }
      ++rowGroupIndex;
    }
  }
}
 
Example 17
Source File: JdepsWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
DotFileFormatter(PrintWriter writer, Archive archive) {
    this.writer = writer;
    this.name = archive.getName();
    writer.format("digraph \"%s\" {%n", name);
    writer.format("    // Path: %s%n", archive.getPathName());
}
 
Example 18
Source File: GNUStyleOptions.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void printUsageTryHelp(PrintWriter out) {
    out.format("%s%n", Main.getMsg("main.usage.summary.try"));
}
 
Example 19
Source File: XssServlet5.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testFormatSafe(PrintWriter pw, String input1,HttpServletRequest req) {
    pw.format(req.getLocale(), "Data : %s", "Constant data");
    pw.format("%s", "SAFE");
    pw.format("%s %s", "SAFE","SAFE");
    pw.format("%s %s %s", "SAFE","SAFE","SAFE");
}
 
Example 20
Source File: GrpcWindmillServer.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public void appendSpecificHtml(PrintWriter writer) {
  writer.format(
      "GetDataStream: %d pending on-wire, %d queued batches", pending.size(), batches.size());
}