Search in sources :

Example 61 with IOError

use of java.io.IOError in project feign by OpenFeign.

the class GenerateTestStubAPT method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    System.out.println(annotations);
    System.out.println(roundEnv);
    final Map<TypeElement, List<ExecutableElement>> clientsToGenerate = annotations.stream().map(roundEnv::getElementsAnnotatedWith).flatMap(Set::stream).map(ExecutableElement.class::cast).collect(Collectors.toMap(annotatedMethod -> TypeElement.class.cast(annotatedMethod.getEnclosingElement()), ImmutableList::of, (list1, list2) -> ImmutableList.<ExecutableElement>builder().addAll(list1).addAll(list2).build()));
    System.out.println("Count: " + clientsToGenerate.size());
    System.out.println("clientsToGenerate: " + clientsToGenerate);
    final Handlebars handlebars = new Handlebars();
    final URLTemplateSource source = new URLTemplateSource("stub.mustache", getClass().getResource("/stub.mustache"));
    Template template;
    try {
        template = handlebars.with(EscapingStrategy.JS).compile(source);
    } catch (final IOException e) {
        throw new IOError(e);
    }
    clientsToGenerate.forEach((type, executables) -> {
        try {
            final String jPackage = readPackage(type);
            final String className = type.getSimpleName().toString();
            final JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(jPackage + "." + className + "Stub");
            final ClientDefinition client = new ClientDefinition(jPackage, className, type.toString());
            final List<MethodDefinition> methods = executables.stream().map(method -> {
                final String methodName = method.getSimpleName().toString();
                final List<ArgumentDefinition> args = method.getParameters().stream().map(var -> new ArgumentDefinition(var.getSimpleName().toString(), var.asType().toString())).collect(Collectors.toList());
                return new MethodDefinition(methodName, method.getReturnType().toString(), method.getReturnType().getKind() == TypeKind.VOID, args);
            }).collect(Collectors.toList());
            final Context context = Context.newBuilder(template).combine("client", client).combine("methods", methods).resolver(JavaBeanValueResolver.INSTANCE, MapValueResolver.INSTANCE, FieldValueResolver.INSTANCE).build();
            final String stubSource = template.apply(context);
            System.out.println(stubSource);
            builderFile.openWriter().append(stubSource).close();
        } catch (final Exception e) {
            e.printStackTrace();
            processingEnv.getMessager().printMessage(Kind.ERROR, "Unable to generate factory for " + type);
        }
    });
    return true;
}
Also used : FieldValueResolver(com.github.jknack.handlebars.context.FieldValueResolver) java.util(java.util) MapValueResolver(com.github.jknack.handlebars.context.MapValueResolver) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) IOError(java.io.IOError) TypeKind(javax.lang.model.type.TypeKind) javax.annotation.processing(javax.annotation.processing) JavaFileObject(javax.tools.JavaFileObject) com.github.jknack.handlebars(com.github.jknack.handlebars) TypeMirror(javax.lang.model.type.TypeMirror) Kind(javax.tools.Diagnostic.Kind) URLTemplateSource(com.github.jknack.handlebars.io.URLTemplateSource) ImmutableList(com.google.common.collect.ImmutableList) Type(java.lang.reflect.Type) AutoService(com.google.auto.service.AutoService) JavaBeanValueResolver(com.github.jknack.handlebars.context.JavaBeanValueResolver) javax.lang.model.element(javax.lang.model.element) WildcardType(javax.lang.model.type.WildcardType) IOException(java.io.IOException) URLTemplateSource(com.github.jknack.handlebars.io.URLTemplateSource) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) IOError(java.io.IOError) ImmutableList(com.google.common.collect.ImmutableList)

Example 62 with IOError

use of java.io.IOError in project checkstyle by checkstyle.

the class CheckerTest method testCatchErrorWithCacheWithNoFileName.

/**
 * Test doesn't need to be serialized.
 *
 * @noinspection SerializableInnerClassWithNonSerializableOuterClass
 */
@Test
public void testCatchErrorWithCacheWithNoFileName() throws Exception {
    final File cacheFile = File.createTempFile("junit", null, temporaryFolder);
    final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
    checkerConfig.addProperty("charset", StandardCharsets.UTF_8.name());
    checkerConfig.addProperty("cacheFile", cacheFile.getPath());
    final String errorMessage = "Java Virtual Machine is broken" + " or has run out of resources necessary for it to continue operating.";
    final Error expectedError = new IOError(new InternalError(errorMessage));
    final File mock = new File("testFile") {

        private static final long serialVersionUID = 1L;

        /**
         * Test is checking catch clause when exception is thrown.
         *
         * @noinspection ProhibitedExceptionThrown
         */
        @Override
        public String getAbsolutePath() {
            throw expectedError;
        }
    };
    final Checker checker = new Checker();
    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
    checker.configure(checkerConfig);
    final List<File> filesToProcess = new ArrayList<>();
    filesToProcess.add(mock);
    try {
        checker.process(filesToProcess);
        assertWithMessage("IOError is expected!").fail();
    }// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
     catch (Error error) {
        assertWithMessage("Error cause differs from IOError").that(error).hasCauseThat().isInstanceOf(IOError.class);
        assertWithMessage("Error message is not expected").that(error).hasCauseThat().hasCauseThat().hasMessageThat().isEqualTo(errorMessage);
        // destroy is called by Main
        checker.destroy();
        final Properties cache = new Properties();
        try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) {
            cache.load(reader);
        }
        assertWithMessage("Cache has unexpected size").that(cache).hasSize(1);
    }
}
Also used : IOError(java.io.IOError) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) IOError(java.io.IOError) Properties(java.util.Properties) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 63 with IOError

use of java.io.IOError in project checkstyle by checkstyle.

the class CheckerTest method testCatchErrorWithCache.

/**
 * Test doesn't need to be serialized.
 *
 * @noinspection SerializableInnerClassWithNonSerializableOuterClass
 */
@Test
public void testCatchErrorWithCache() throws Exception {
    final File cacheFile = File.createTempFile("junit", null, temporaryFolder);
    final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
    checkerConfig.addProperty("charset", StandardCharsets.UTF_8.name());
    checkerConfig.addProperty("cacheFile", cacheFile.getPath());
    final String errorMessage = "Java Virtual Machine is broken" + " or has run out of resources necessary for it to continue operating.";
    final Error expectedError = new IOError(new InternalError(errorMessage));
    final File mock = new File("testFile") {

        private static final long serialVersionUID = 1L;

        @Override
        public String getAbsolutePath() {
            return "testFile";
        }

        /**
         * Test is checking catch clause when exception is thrown.
         *
         * @noinspection ProhibitedExceptionThrown
         */
        @Override
        public File getAbsoluteFile() {
            throw expectedError;
        }
    };
    final Checker checker = new Checker();
    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
    checker.configure(checkerConfig);
    final List<File> filesToProcess = new ArrayList<>();
    filesToProcess.add(mock);
    try {
        checker.process(filesToProcess);
        assertWithMessage("IOError is expected!").fail();
    }// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
     catch (Error error) {
        assertWithMessage("Error cause differs from IOError").that(error.getCause()).isInstanceOf(IOError.class);
        assertWithMessage("Error message is not expected").that(error).hasCauseThat().hasCauseThat().hasMessageThat().isEqualTo(errorMessage);
        // destroy is called by Main
        checker.destroy();
        final Properties cache = new Properties();
        try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) {
            cache.load(reader);
        }
        assertWithMessage("Cache has unexpected size").that(cache).hasSize(1);
        assertWithMessage("testFile is not in cache").that(cache.getProperty("testFile")).isNull();
    }
}
Also used : IOError(java.io.IOError) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) IOError(java.io.IOError) Properties(java.util.Properties) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 64 with IOError

use of java.io.IOError in project checkstyle by checkstyle.

the class CheckerTest method testCatchErrorInProcessFilesMethod.

/**
 * Test doesn't need to be serialized.
 *
 * @noinspection SerializableInnerClassWithNonSerializableOuterClass
 */
@Test
public void testCatchErrorInProcessFilesMethod() throws Exception {
    // Assume that I/O error is happened when we try to invoke 'lastModified()' method.
    final String errorMessage = "Java Virtual Machine is broken" + " or has run out of resources necessary for it to continue operating.";
    final Error expectedError = new IOError(new InternalError(errorMessage));
    final File mock = new File("testFile") {

        private static final long serialVersionUID = 1L;

        /**
         * Test is checking catch clause when exception is thrown.
         *
         * @noinspection ProhibitedExceptionThrown
         */
        @Override
        public long lastModified() {
            throw expectedError;
        }
    };
    final Checker checker = new Checker();
    final List<File> filesToProcess = new ArrayList<>();
    filesToProcess.add(mock);
    try {
        checker.process(filesToProcess);
        assertWithMessage("IOError is expected!").fail();
    }// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
     catch (Error error) {
        assertWithMessage("Error cause differs from IOError").that(error.getCause()).isInstanceOf(IOError.class);
        assertWithMessage("Error cause is not InternalError").that(error.getCause().getCause()).isInstanceOf(InternalError.class);
        assertWithMessage("Error message is not expected").that(error).hasCauseThat().hasCauseThat().hasMessageThat().isEqualTo(errorMessage);
    }
}
Also used : IOError(java.io.IOError) ArrayList(java.util.ArrayList) IOError(java.io.IOError) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 65 with IOError

use of java.io.IOError in project azure-iot-sdk-java by Azure.

the class InternalClient method setOption_SetSendInterval.

void setOption_SetSendInterval(Object value) {
    if (value != null) {
        // Codes_SRS_DEVICECLIENT_21_041: ["SetSendInterval" needs to have value type long.]
        if (value instanceof Long) {
            try {
                verifyRegisteredIfMultiplexing();
                log.info("Setting send period to {} milliseconds", value);
                this.deviceIO.setSendPeriodInMilliseconds((long) value);
            } catch (IOException e) {
                throw new IOError(e);
            }
        } else {
            throw new IllegalArgumentException("value is not long = " + value);
        }
    }
}
Also used : IOError(java.io.IOError) IOException(java.io.IOException)

Aggregations

IOError (java.io.IOError)78 IOException (java.io.IOException)58 File (java.io.File)11 ArrayList (java.util.ArrayList)8 Path (java.nio.file.Path)5 Status (ch.qos.logback.core.status.Status)4 BufferedReader (java.io.BufferedReader)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Console (java.io.Console)4 DataInputStream (java.io.DataInputStream)4 IPartitioner (org.apache.cassandra.dht.IPartitioner)4 FastByteArrayInputStream (org.apache.cassandra.io.util.FastByteArrayInputStream)4 Test (org.junit.Test)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 InputStream (java.io.InputStream)3 ByteBuffer (java.nio.ByteBuffer)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 QueryPath (org.apache.cassandra.db.filter.QueryPath)3 CorruptSSTableException (org.apache.cassandra.io.sstable.CorruptSSTableException)3 SSTableReader (org.apache.cassandra.io.sstable.format.SSTableReader)3