All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.code.PeerResourceBuilder Maven / Gradle / Ivy

/*
 * Copyright 2016 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.code;

import static br.com.objectos.code.ProcessingEnvironmentWrapper.FILE_SEPARATOR;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Path;
import java.util.Objects;

import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.FileObject;
import javax.tools.StandardLocation;

/**
 * @author [email protected] (Marcio Endo)
 */
public class PeerResourceBuilder {

  private final String fileName;

  private String contents;

  public PeerResourceBuilder(TypeInfo typeInfo, String suffix) {
    String qualifiedName = typeInfo.qualifiedName();
    String fileName = qualifiedName.replace(".", FILE_SEPARATOR);
    this.fileName = fileName + "." + suffix;
  }

  public Artifact build() {
    return new Artifact() {
      @Override
      public String toString() {
        return contents;
      }

      @Override
      public void writeTo(Path path) {
        throw new UnsupportedOperationException();
      }

      @Override
      protected void execute(ProcessingEnvironment processingEnv) {
        try {
          tryToWrite(processingEnv);
        } catch (IOException e) {
          log(processingEnv, e);
        }
      }
    };
  }

  public PeerResourceBuilder contents(String contents) {
    this.contents = Objects.requireNonNull(contents);
    return this;
  }

  private void tryToWrite(ProcessingEnvironment processingEnv) throws IOException {
    Filer filer = processingEnv.getFiler();
    FileObject file = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", fileName);
    try (OutputStream out = file.openOutputStream()) {
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
      writer.write(contents);
      writer.flush();
    }
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy