repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
JosuaKrause/NBTEditor
src/nbt/record/NBTList.java
// Path: src/nbt/write/ByteWriter.java // public class ByteWriter implements Closeable { // // /** // * The utf-8 charset. // */ // public static final Charset UTF8 = Charset.forName("UTF-8"); // // private OutputStream out; // // /** // * Creates a byte writer for an output stream. // * // * @param out The output stream. // */ // public ByteWriter(final OutputStream out) { // this.out = out; // } // // /** // * Writes a single byte. // * // * @param b The byte. // * @throws IOException I/O Exception. // */ // public final void write(final byte b) throws IOException { // out.write(b); // } // // /** // * Writes a short. // * // * @param s The short. // * @throws IOException I/O Exception. // */ // public final void write(final short s) throws IOException { // writeBigEndian(s, 2); // } // // /** // * Writes an integer. // * // * @param i The integer. // * @throws IOException I/O Exception. // */ // public final void write(final int i) throws IOException { // writeBigEndian(i, 4); // } // // /** // * Writes a long. // * // * @param l The long. // * @throws IOException I/O Exception. // */ // public final void write(final long l) throws IOException { // writeBigEndian(l, 8); // } // // /** // * Writes a float. // * // * @param f The float. // * @throws IOException I/O Exception. // */ // public final void write(final float f) throws IOException { // write(Float.floatToIntBits(f)); // } // // /** // * Writes a double. // * // * @param f The double. // * @throws IOException I/O Exception. // */ // public final void write(final double f) throws IOException { // write(Double.doubleToLongBits(f)); // } // // /** // * Writes a byte array. Note that this is <em>not</em> equivalent to // * successive {@link #write(byte)} calls! // * // * @param arr The array. // * @throws IOException I/O Exception. // */ // public final void write(final byte[] arr) throws IOException { // write(arr.length); // out.write(arr); // } // // /** // * Writes an integer array. Note that this is <em>not</em> equivalent to // * successive {@link #write(int)} calls! // * // * @param arr The array. // * @throws IOException I/O Exception. // */ // public final void write(final int[] arr) throws IOException { // write(arr.length); // for(final int i : arr) { // write(i); // } // } // // /** // * Writes a string. // * // * @param str The string. // * @throws IOException I/O Exception. // */ // public final void write(final String str) throws IOException { // final byte[] arr = str.getBytes(UTF8); // write((short) arr.length); // out.write(arr); // } // // private void writeBigEndian(final long bytes, final int count) // throws IOException { // long lb = bytes; // final byte[] b = new byte[count]; // int i = count; // while(--i >= 0) { // b[i] = (byte) lb; // lb >>>= 8; // } // out.write(b); // } // // @Override // public void close() throws IOException { // if(out != null) { // final OutputStream t = out; // out = null; // t.close(); // } // } // // @Override // protected void finalize() throws Throwable { // close(); // super.finalize(); // } // // }
import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import nbt.write.ByteWriter;
for(final NBTRecord r : records) { if(r.hasChanged()) return true; } return false; } @Override public void resetChange() { super.resetChange(); for(final NBTRecord r : records) { r.resetChange(); } } @Override public String getTypeInfo() { return super.getTypeInfo() + " " + type; } @Override public boolean hasSize() { return true; } @Override public int size() { return getLength(); } @Override
// Path: src/nbt/write/ByteWriter.java // public class ByteWriter implements Closeable { // // /** // * The utf-8 charset. // */ // public static final Charset UTF8 = Charset.forName("UTF-8"); // // private OutputStream out; // // /** // * Creates a byte writer for an output stream. // * // * @param out The output stream. // */ // public ByteWriter(final OutputStream out) { // this.out = out; // } // // /** // * Writes a single byte. // * // * @param b The byte. // * @throws IOException I/O Exception. // */ // public final void write(final byte b) throws IOException { // out.write(b); // } // // /** // * Writes a short. // * // * @param s The short. // * @throws IOException I/O Exception. // */ // public final void write(final short s) throws IOException { // writeBigEndian(s, 2); // } // // /** // * Writes an integer. // * // * @param i The integer. // * @throws IOException I/O Exception. // */ // public final void write(final int i) throws IOException { // writeBigEndian(i, 4); // } // // /** // * Writes a long. // * // * @param l The long. // * @throws IOException I/O Exception. // */ // public final void write(final long l) throws IOException { // writeBigEndian(l, 8); // } // // /** // * Writes a float. // * // * @param f The float. // * @throws IOException I/O Exception. // */ // public final void write(final float f) throws IOException { // write(Float.floatToIntBits(f)); // } // // /** // * Writes a double. // * // * @param f The double. // * @throws IOException I/O Exception. // */ // public final void write(final double f) throws IOException { // write(Double.doubleToLongBits(f)); // } // // /** // * Writes a byte array. Note that this is <em>not</em> equivalent to // * successive {@link #write(byte)} calls! // * // * @param arr The array. // * @throws IOException I/O Exception. // */ // public final void write(final byte[] arr) throws IOException { // write(arr.length); // out.write(arr); // } // // /** // * Writes an integer array. Note that this is <em>not</em> equivalent to // * successive {@link #write(int)} calls! // * // * @param arr The array. // * @throws IOException I/O Exception. // */ // public final void write(final int[] arr) throws IOException { // write(arr.length); // for(final int i : arr) { // write(i); // } // } // // /** // * Writes a string. // * // * @param str The string. // * @throws IOException I/O Exception. // */ // public final void write(final String str) throws IOException { // final byte[] arr = str.getBytes(UTF8); // write((short) arr.length); // out.write(arr); // } // // private void writeBigEndian(final long bytes, final int count) // throws IOException { // long lb = bytes; // final byte[] b = new byte[count]; // int i = count; // while(--i >= 0) { // b[i] = (byte) lb; // lb >>>= 8; // } // out.write(b); // } // // @Override // public void close() throws IOException { // if(out != null) { // final OutputStream t = out; // out = null; // t.close(); // } // } // // @Override // protected void finalize() throws Throwable { // close(); // super.finalize(); // } // // } // Path: src/nbt/record/NBTList.java import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import nbt.write.ByteWriter; for(final NBTRecord r : records) { if(r.hasChanged()) return true; } return false; } @Override public void resetChange() { super.resetChange(); for(final NBTRecord r : records) { r.resetChange(); } } @Override public String getTypeInfo() { return super.getTypeInfo() + " " + type; } @Override public boolean hasSize() { return true; } @Override public int size() { return getLength(); } @Override
public void writePayload(final ByteWriter out) throws IOException {
rujews/android-gradle-book-code
chapter06/example68/app/src/main/java/org/flysnow/androidgradlebook/ex68/app/HelloWorld.java
// Path: chapter06/example68/base/src/main/java/org/flysnow/androidgradlebook/ex68/base/Person.java // public class Person { // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // }
import org.flysnow.androidgradlebook.ex68.base.Person;
package org.flysnow.androidgradlebook.ex68.app; /** * Created by 飞雪无情 on 16-1-24. */ public class HelloWorld { public static void main(String[] args){
// Path: chapter06/example68/base/src/main/java/org/flysnow/androidgradlebook/ex68/base/Person.java // public class Person { // private String name; // private int age; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Person{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } // } // Path: chapter06/example68/app/src/main/java/org/flysnow/androidgradlebook/ex68/app/HelloWorld.java import org.flysnow.androidgradlebook.ex68.base.Person; package org.flysnow.androidgradlebook.ex68.app; /** * Created by 飞雪无情 on 16-1-24. */ public class HelloWorld { public static void main(String[] args){
Person person =new Person();
openstack/monasca-persister
java/src/main/java/monasca/persister/consumer/KafkaConsumerRunnableBasic.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import monasca.persister.repository.RepoException; import monasca.persister.pipeline.ManagedPipeline; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import kafka.consumer.ConsumerIterator;
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Copyright (c) 2017 SUSE LLC. * * 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 monasca.persister.consumer; public class KafkaConsumerRunnableBasic<T> implements Runnable { private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerRunnableBasic.class); private final KafkaChannel kafkaChannel; private final String threadId; private final ManagedPipeline<T> pipeline; private volatile boolean stop = false; private boolean active = false; private ExecutorService executorService; @Inject public KafkaConsumerRunnableBasic(@Assisted KafkaChannel kafkaChannel, @Assisted ManagedPipeline<T> pipeline, @Assisted String threadId) { this.kafkaChannel = kafkaChannel; this.pipeline = pipeline; this.threadId = threadId; } public KafkaConsumerRunnableBasic<T> setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; }
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/consumer/KafkaConsumerRunnableBasic.java import monasca.persister.repository.RepoException; import monasca.persister.pipeline.ManagedPipeline; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import kafka.consumer.ConsumerIterator; /* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Copyright (c) 2017 SUSE LLC. * * 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 monasca.persister.consumer; public class KafkaConsumerRunnableBasic<T> implements Runnable { private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerRunnableBasic.class); private final KafkaChannel kafkaChannel; private final String threadId; private final ManagedPipeline<T> pipeline; private volatile boolean stop = false; private boolean active = false; private ExecutorService executorService; @Inject public KafkaConsumerRunnableBasic(@Assisted KafkaChannel kafkaChannel, @Assisted ManagedPipeline<T> pipeline, @Assisted String threadId) { this.kafkaChannel = kafkaChannel; this.pipeline = pipeline; this.threadId = threadId; } public KafkaConsumerRunnableBasic<T> setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; }
protected void publishHeartbeat() throws RepoException {
openstack/monasca-persister
java/src/main/java/monasca/persister/repository/influxdb/InfluxV9AlarmRepo.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException; import monasca.common.model.event.AlarmStateTransitionedEvent; import com.google.inject.Inject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger;
/* * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP * * 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 monasca.persister.repository.influxdb; public class InfluxV9AlarmRepo extends InfluxAlarmRepo { private static final Logger logger = LoggerFactory.getLogger(InfluxV9AlarmRepo.class); private final InfluxV9RepoWriter influxV9RepoWriter; private final ObjectMapper objectMapper = new ObjectMapper(); private final DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime(); @Inject public InfluxV9AlarmRepo( final Environment env, final InfluxV9RepoWriter influxV9RepoWriter) { super(env); this.influxV9RepoWriter = influxV9RepoWriter; this.objectMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } @Override
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/repository/influxdb/InfluxV9AlarmRepo.java import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException; import monasca.common.model.event.AlarmStateTransitionedEvent; import com.google.inject.Inject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; /* * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP * * 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 monasca.persister.repository.influxdb; public class InfluxV9AlarmRepo extends InfluxAlarmRepo { private static final Logger logger = LoggerFactory.getLogger(InfluxV9AlarmRepo.class); private final InfluxV9RepoWriter influxV9RepoWriter; private final ObjectMapper objectMapper = new ObjectMapper(); private final DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime(); @Inject public InfluxV9AlarmRepo( final Environment env, final InfluxV9RepoWriter influxV9RepoWriter) { super(env); this.influxV9RepoWriter = influxV9RepoWriter; this.objectMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } @Override
protected int write(String id) throws RepoException {
openstack/monasca-persister
java/src/main/java/monasca/persister/pipeline/event/AlarmStateTransitionHandler.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import monasca.common.model.event.AlarmStateTransitionedEvent; import monasca.persister.configuration.PipelineConfig; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.codahale.metrics.Counter; import com.fasterxml.jackson.databind.DeserializationFeature; import io.dropwizard.setup.Environment; import monasca.persister.repository.Repo; import monasca.persister.repository.RepoException;
logger.error("[{}]: failed to deserialize message {}", this.threadId, msg, e); return 0; } logger.debug("[{}]: [{}:{}] {}", this.threadId, this.getBatchCount(), this.getMsgCount(), alarmStateTransitionedEvent); this.alarmRepo.addToBatch(alarmStateTransitionedEvent, this.threadId); this.alarmStateTransitionCounter.inc(); return 1; } @Override protected void initObjectMapper() { this.objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); this.objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); this.objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); } @Override
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/pipeline/event/AlarmStateTransitionHandler.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import monasca.common.model.event.AlarmStateTransitionedEvent; import monasca.persister.configuration.PipelineConfig; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.codahale.metrics.Counter; import com.fasterxml.jackson.databind.DeserializationFeature; import io.dropwizard.setup.Environment; import monasca.persister.repository.Repo; import monasca.persister.repository.RepoException; logger.error("[{}]: failed to deserialize message {}", this.threadId, msg, e); return 0; } logger.debug("[{}]: [{}:{}] {}", this.threadId, this.getBatchCount(), this.getMsgCount(), alarmStateTransitionedEvent); this.alarmRepo.addToBatch(alarmStateTransitionedEvent, this.threadId); this.alarmStateTransitionCounter.inc(); return 1; } @Override protected void initObjectMapper() { this.objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); this.objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); this.objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); } @Override
protected int flushRepository() throws RepoException {
openstack/monasca-persister
java/src/main/java/monasca/persister/repository/influxdb/InfluxV9RepoWriter.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import monasca.persister.configuration.PersisterConfig; import monasca.persister.repository.RepoException; import com.google.inject.Inject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap;
} } }).addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }).build(); } else { this.httpClient = HttpClients.custom().setConnectionManager(cm).build(); } }
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/repository/influxdb/InfluxV9RepoWriter.java import monasca.persister.configuration.PersisterConfig; import monasca.persister.repository.RepoException; import com.google.inject.Inject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; } } }).addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }).build(); } else { this.httpClient = HttpClients.custom().setConnectionManager(cm).build(); } }
protected int write(final InfluxPoint[] influxPointArry, String id) throws RepoException {
openstack/monasca-persister
java/src/main/java/monasca/persister/repository/cassandra/CassandraRepo.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Counter; import com.codahale.metrics.Timer; import com.datastax.driver.core.BatchStatement; import com.datastax.driver.core.BatchStatement.Type; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.core.exceptions.BootstrappingException; import com.datastax.driver.core.exceptions.DriverException; import com.datastax.driver.core.exceptions.NoHostAvailableException; import com.datastax.driver.core.exceptions.OperationTimedOutException; import com.datastax.driver.core.exceptions.OverloadedException; import com.datastax.driver.core.exceptions.QueryConsistencyException; import com.datastax.driver.core.exceptions.UnavailableException; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException;
} else { logger.warn("[{}]: Query failed, retrying {} of {}: {} ", id, retryCount, maxWriteRetries, e.getMessage()); try { Thread.sleep(1000 * (1 << retryCount)); } catch (InterruptedException ie) { logger.debug("[{}]: Interrupted: {}", id, ie); } _executeQuery(id, query, startTime, retryCount++); } } public int handleFlush_batch(String id) { Statement query; int flushedCount = 0; BatchStatement batch = new BatchStatement(Type.UNLOGGED); while ((query = queue.poll()) != null) { flushedCount++; batch.add(query); } executeQuery(id, batch, System.nanoTime()); metricCompleted.inc(flushedCount); return flushedCount; }
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/repository/cassandra/CassandraRepo.java import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Counter; import com.codahale.metrics.Timer; import com.datastax.driver.core.BatchStatement; import com.datastax.driver.core.BatchStatement.Type; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.core.exceptions.BootstrappingException; import com.datastax.driver.core.exceptions.DriverException; import com.datastax.driver.core.exceptions.NoHostAvailableException; import com.datastax.driver.core.exceptions.OperationTimedOutException; import com.datastax.driver.core.exceptions.OverloadedException; import com.datastax.driver.core.exceptions.QueryConsistencyException; import com.datastax.driver.core.exceptions.UnavailableException; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException; } else { logger.warn("[{}]: Query failed, retrying {} of {}: {} ", id, retryCount, maxWriteRetries, e.getMessage()); try { Thread.sleep(1000 * (1 << retryCount)); } catch (InterruptedException ie) { logger.debug("[{}]: Interrupted: {}", id, ie); } _executeQuery(id, query, startTime, retryCount++); } } public int handleFlush_batch(String id) { Statement query; int flushedCount = 0; BatchStatement batch = new BatchStatement(Type.UNLOGGED); while ((query = queue.poll()) != null) { flushedCount++; batch.add(query); } executeQuery(id, batch, System.nanoTime()); metricCompleted.inc(flushedCount); return flushedCount; }
public int handleFlush(String id) throws RepoException {
openstack/monasca-persister
java/src/main/java/monasca/persister/repository/influxdb/InfluxV9MetricRepo.java
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.google.inject.Inject; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException;
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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 monasca.persister.repository.influxdb; public class InfluxV9MetricRepo extends InfluxMetricRepo { private final InfluxV9RepoWriter influxV9RepoWriter; @Inject public InfluxV9MetricRepo( final Environment env, final InfluxV9RepoWriter influxV9RepoWriter) { super(env); this.influxV9RepoWriter = influxV9RepoWriter; } @Override
// Path: java/src/main/java/monasca/persister/repository/RepoException.java // public class RepoException extends Exception { // // public RepoException() { // // super(); // } // // public RepoException(String message) { // // super(message); // } // // public RepoException(String message, Throwable cause) { // // super(message, cause); // } // // public RepoException(Throwable cause) { // // super(cause); // } // // protected RepoException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: java/src/main/java/monasca/persister/repository/influxdb/InfluxV9MetricRepo.java import com.google.inject.Inject; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.dropwizard.setup.Environment; import monasca.persister.repository.RepoException; /* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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 monasca.persister.repository.influxdb; public class InfluxV9MetricRepo extends InfluxMetricRepo { private final InfluxV9RepoWriter influxV9RepoWriter; @Inject public InfluxV9MetricRepo( final Environment env, final InfluxV9RepoWriter influxV9RepoWriter) { super(env); this.influxV9RepoWriter = influxV9RepoWriter; } @Override
protected int write(String id) throws RepoException {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/entities/present/PresentAccepted.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // }
import info.interactivesystems.gamificationengine.entities.Organisation; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
package info.interactivesystems.gamificationengine.entities.present; /** * Presents that are in the in-box of the board a player can accept or deny. If the player * accept a present its status is set to accepted and an PresentAccepted object is created. */ @Entity @JsonIgnoreProperties({ "belongsTo" }) public class PresentAccepted { enum Status { ACCEPT, DENIED } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @ManyToOne
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/entities/present/PresentAccepted.java import info.interactivesystems.gamificationengine.entities.Organisation; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; package info.interactivesystems.gamificationengine.entities.present; /** * Presents that are in the in-box of the board a player can accept or deny. If the player * accept a present its status is set to accepted and an PresentAccepted object is created. */ @Entity @JsonIgnoreProperties({ "belongsTo" }) public class PresentAccepted { enum Status { ACCEPT, DENIED } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @ManyToOne
private Organisation belongsTo;
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/dao/AccountDAO.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Account.java // @Entity // @JsonIgnoreProperties({"password"}) // public class Account implements Serializable { // // private static final long serialVersionUID = -683022088070098L; // // @Id // @NotNull // private String email; // // @NotNull // private String password; // // private String firstName; // // private String lastName; // // public Account(String email) { // super(); // this.email = email; // } // // public Account() { // super(); // } // // /** // * Gets the email address of an Account. // * This email address is unique. // * // * @return String representing the email address. // */ // public String getEmail() { // return email; // } // // /** // * Set the email address for an Account. // * This email address has to be unique. // * // * @param email // * the email address for the Account // */ // public void setEmail(@NotNull String email) { // this.email = email; // } // // /** // * Gets the password for the Account. // * // * @return String representing the password. // */ // public String getPassword() { // return password; // } // // /** // * Sets the password for the Account. // * // * @param password // * the password for the Account // */ // public void setPassword(@NotNull String password) { // this.password = password; // } // // /** // * Gets the first name of the Account user. // * // * @return String representing the first Name. // */ // public String getFirstName() { // return firstName; // } // // /** // * Sets the first name of the Account user. // * // * @param firstName // * the first name of the Account user // */ // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // /** // * Gets the last name of the Account user. // * // * @return String representing the last name. // */ // public String getLastName() { // return lastName; // } // // /** // * Sets the last name of the Account user. // * // * @param lastName // * the last name of the Account user // */ // public void setLastName(String lastName) { // this.lastName = lastName; // } // // /** // * Checks if the passed password is equal to the hashed password. // * // * @param checkPassword // * The password that should be checked. // * @return Returns a boolean value if the passed password is equal to the hashed password (true) else false. // */ // public boolean checkPassword(String checkPassword) { // return this.password.equals(checkPassword); // } // }
import info.interactivesystems.gamificationengine.entities.Account; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query;
package info.interactivesystems.gamificationengine.dao; /** * Data access for an account. */ @Named @Stateless
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Account.java // @Entity // @JsonIgnoreProperties({"password"}) // public class Account implements Serializable { // // private static final long serialVersionUID = -683022088070098L; // // @Id // @NotNull // private String email; // // @NotNull // private String password; // // private String firstName; // // private String lastName; // // public Account(String email) { // super(); // this.email = email; // } // // public Account() { // super(); // } // // /** // * Gets the email address of an Account. // * This email address is unique. // * // * @return String representing the email address. // */ // public String getEmail() { // return email; // } // // /** // * Set the email address for an Account. // * This email address has to be unique. // * // * @param email // * the email address for the Account // */ // public void setEmail(@NotNull String email) { // this.email = email; // } // // /** // * Gets the password for the Account. // * // * @return String representing the password. // */ // public String getPassword() { // return password; // } // // /** // * Sets the password for the Account. // * // * @param password // * the password for the Account // */ // public void setPassword(@NotNull String password) { // this.password = password; // } // // /** // * Gets the first name of the Account user. // * // * @return String representing the first Name. // */ // public String getFirstName() { // return firstName; // } // // /** // * Sets the first name of the Account user. // * // * @param firstName // * the first name of the Account user // */ // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // /** // * Gets the last name of the Account user. // * // * @return String representing the last name. // */ // public String getLastName() { // return lastName; // } // // /** // * Sets the last name of the Account user. // * // * @param lastName // * the last name of the Account user // */ // public void setLastName(String lastName) { // this.lastName = lastName; // } // // /** // * Checks if the passed password is equal to the hashed password. // * // * @param checkPassword // * The password that should be checked. // * @return Returns a boolean value if the passed password is equal to the hashed password (true) else false. // */ // public boolean checkPassword(String checkPassword) { // return this.password.equals(checkPassword); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/dao/AccountDAO.java import info.interactivesystems.gamificationengine.entities.Account; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; package info.interactivesystems.gamificationengine.dao; /** * Data access for an account. */ @Named @Stateless
public class AccountDAO extends AbstractDAO<Account> {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/utils/StringUtils.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // }
import info.interactivesystems.gamificationengine.api.exeption.ApiError; import info.interactivesystems.gamificationengine.api.validation.ValidListOfDigits; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Response;
package info.interactivesystems.gamificationengine.utils; public class StringUtils { /** * Converts a string of digits to list of integers. * <p></p> * Splits a comma separated list by a comma and trims each string. Collects to * a list of Integers. * * @param commaSeparatedList * The comma separated list. * @return The list of single integers that were separated. */ public static @NotNull List<Integer> stringArrayToIntegerList(@NotNull String commaSeparatedList) { String[] arrayList = commaSeparatedList.split(","); return Stream.of(arrayList).map(String::trim).collect(Collectors.mapping(Integer::valueOf, Collectors.toList())); } /** * Checks if the passed value is a list of digists. * * @param value * The value for validation. * @return If valid the identity is returned. */ public static @NotNull String validateAsListOfDigits(@NotNull @ValidListOfDigits String value) { return value; } /** * Checks if the passed value is "true", "t", "yes", "y", "sure", "aye", "ja" or "1". If this is the case it is * accepted as a value for "true" and so true is returned else false. * * @param value * The value that should be checked. * @return * Boolean value if the passed String is */ public static boolean checkBoolean(String value){ boolean result = "true".equalsIgnoreCase(value) || "t".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "sure".equalsIgnoreCase(value) || "aye".equalsIgnoreCase(value) || "ja".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value); return result; } /** * This method prints the ids of objects that should be deleted before a specific object can be deleted. * * @param ids * Ids of the objects that should be deleted first. * @param objectToDelete * The type of the object that should be deleted. This is only given by a String. * @param type * The type of the object that use the object, so it should be deleted before. This is only given * by a String. */ public static void printIdsForDeletion(List<String> ids, String objectToDelete, String type){ String message = "This " +objectToDelete + " is still used. Please delete first " + type + " with id: "; message += String.join(",", ids);
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/utils/StringUtils.java import info.interactivesystems.gamificationengine.api.exeption.ApiError; import info.interactivesystems.gamificationengine.api.validation.ValidListOfDigits; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Response; package info.interactivesystems.gamificationengine.utils; public class StringUtils { /** * Converts a string of digits to list of integers. * <p></p> * Splits a comma separated list by a comma and trims each string. Collects to * a list of Integers. * * @param commaSeparatedList * The comma separated list. * @return The list of single integers that were separated. */ public static @NotNull List<Integer> stringArrayToIntegerList(@NotNull String commaSeparatedList) { String[] arrayList = commaSeparatedList.split(","); return Stream.of(arrayList).map(String::trim).collect(Collectors.mapping(Integer::valueOf, Collectors.toList())); } /** * Checks if the passed value is a list of digists. * * @param value * The value for validation. * @return If valid the identity is returned. */ public static @NotNull String validateAsListOfDigits(@NotNull @ValidListOfDigits String value) { return value; } /** * Checks if the passed value is "true", "t", "yes", "y", "sure", "aye", "ja" or "1". If this is the case it is * accepted as a value for "true" and so true is returned else false. * * @param value * The value that should be checked. * @return * Boolean value if the passed String is */ public static boolean checkBoolean(String value){ boolean result = "true".equalsIgnoreCase(value) || "t".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "sure".equalsIgnoreCase(value) || "aye".equalsIgnoreCase(value) || "ja".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value); return result; } /** * This method prints the ids of objects that should be deleted before a specific object can be deleted. * * @param ids * Ids of the objects that should be deleted first. * @param objectToDelete * The type of the object that should be deleted. This is only given by a String. * @param type * The type of the object that use the object, so it should be deleted before. This is only given * by a String. */ public static void printIdsForDeletion(List<String> ids, String objectToDelete, String type){ String message = "This " +objectToDelete + " is still used. Please delete first " + type + " with id: "; message += String.join(",", ids);
throw new ApiError(Response.Status.FORBIDDEN, message);
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/utils/SecurityTools.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // }
import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.UUID; import javax.ws.rs.core.Response; import info.interactivesystems.gamificationengine.api.exeption.ApiError;
package info.interactivesystems.gamificationengine.utils; public class SecurityTools { private SecurityTools() { } /** * Generates API-Key by creating a new universal unique identifier (UUID). * TODO: Maybe change this to a encrypted timestamp/salt pair to decrypt * creation date. * * @return A randomly generated code used as API key */ public static String generateApiKey() { return UUID.randomUUID().toString(); } /** * Encodes a password to a encoded password with SHA 512. * @param plainText * The original password. * @return An encoded password. */ //Based on http://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java public static String encryptWithSHA512(String plainText) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-512"); md.update(plainText.getBytes("UTF-8")); byte[] hashedPW = md.digest(); String encoded = Base64.getEncoder().encodeToString(hashedPW); return encoded; } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/utils/SecurityTools.java import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.UUID; import javax.ws.rs.core.Response; import info.interactivesystems.gamificationengine.api.exeption.ApiError; package info.interactivesystems.gamificationengine.utils; public class SecurityTools { private SecurityTools() { } /** * Generates API-Key by creating a new universal unique identifier (UUID). * TODO: Maybe change this to a encrypted timestamp/salt pair to decrypt * creation date. * * @return A randomly generated code used as API key */ public static String generateApiKey() { return UUID.randomUUID().toString(); } /** * Encodes a password to a encoded password with SHA 512. * @param plainText * The original password. * @return An encoded password. */ //Based on http://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java public static String encryptWithSHA512(String plainText) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-512"); md.update(plainText.getBytes("UTF-8")); byte[] hashedPW = md.digest(); String encoded = Base64.getEncoder().encodeToString(hashedPW); return encoded; } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new ApiError(Response.Status.FORBIDDEN, "The password cannot be hashed.");
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/entities/present/PresentArchived.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // }
import info.interactivesystems.gamificationengine.entities.Organisation; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
package info.interactivesystems.gamificationengine.entities.present; /** * Presents that are accepted a player can archived. If the player archived a present * an PresentArchived object is created. * */ @Entity @JsonIgnoreProperties({ "belongsTo" }) public class PresentArchived { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @ManyToOne
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/entities/present/PresentArchived.java import info.interactivesystems.gamificationengine.entities.Organisation; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; package info.interactivesystems.gamificationengine.entities.present; /** * Presents that are accepted a player can archived. If the player archived a present * an PresentArchived object is created. * */ @Entity @JsonIgnoreProperties({ "belongsTo" }) public class PresentArchived { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @ManyToOne
private Organisation belongsTo;
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/dao/OrganisationDAO.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // }
import info.interactivesystems.gamificationengine.entities.Organisation; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query;
package info.interactivesystems.gamificationengine.dao; /** * Data access for developer organisations. */ @Named @Stateless public class OrganisationDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new organisation in the data base. * * @param organisation * The {@link Organisation} that should be stored in the data base. */
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Organisation.java // @Entity // public class Organisation implements Serializable { // // private static final long serialVersionUID = -6830220885028070098L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // private Collection<Account> managers; // // private String name; // // @NotNull // @Column(unique = true) // private String apiKey; // // public Organisation(String name) { // super(); // this.name = name; // managers = new HashSet<Account>(); // } // // public Organisation() { // super(); // managers = new HashSet<Account>(); // } // // /** // * Sets the id of the created organisation. // * // * @param id // * The new id of the organisation // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation's id. // * // * @return organisation's id as int // */ // public int getId() { // return id; // } // // /** // * Gets all accounts of the organisation which are associated to this organisation. // * Each account belongs to a manager. // * // * @return Collection of all organisation's manager accounts // */ // public Collection<Account> getManagers() { // return managers; // } // // /** // * Sets the list of the organisation's accounts. Each account belongs to a // * manager. // * // * @param managers // * List of all organisation's accounts // */ // public void setManagers(Collection<Account> managers) { // this.managers = managers; // } // // /** // * Gets the organisation's name and returns it as a String. // * // * @return name of the organisation as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an organisation. // * // * @param name // * The name of the organisation. // * // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation's unique API key and returns it. // * // * @return the apiKey as a String // */ // public String getApiKey() { // return apiKey; // } // // /** // * Sets the organisation's API key. // * // * @param apiKey // * The API key which is unique and specific for one organisation. // */ // public void setApiKey(@NotNull String apiKey) { // this.apiKey = apiKey; // } // // /** // * Adds a new manager's account to the organisation's list of accounts. // * // * @param account // * which should be added to the list // */ // public void addManager(@NotNull Account account) { // this.managers.add(account); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/dao/OrganisationDAO.java import info.interactivesystems.gamificationengine.entities.Organisation; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; package info.interactivesystems.gamificationengine.dao; /** * Data access for developer organisations. */ @Named @Stateless public class OrganisationDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new organisation in the data base. * * @param organisation * The {@link Organisation} that should be stored in the data base. */
public void insertOrganisation(Organisation organisation) {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/exeption/ResteasyViolationExceptionMapper.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java // public class ResponseSurrogate<T> { // // @SuppressWarnings("FieldCanBeLocal") // // @JsonUnwrapped // @JsonProperty // final T content; // // @JsonProperty // final Response.Status contentResponseType; // // @SuppressWarnings("FieldCanBeLocal") // @JsonProperty // final List<ErrorMessage> info; // // private ResponseSurrogate(T content, Response.Status contentResponseType, Notification info) { // this.content = content; // this.contentResponseType = contentResponseType; // this.info = info.getErrors(); // } // // public static <T> Response of(Response.Status status, MediaType mediaType, T content, Response.Status contentType, Notification notification) { // status = Optional.ofNullable(status).orElse(Response.Status.OK); // mediaType = Optional.ofNullable(mediaType).orElse(MediaType.APPLICATION_JSON_TYPE); // // notification = Optional.ofNullable(notification).orElse(new Notification()); // // if (content == null) { // contentType = Response.Status.BAD_REQUEST; // } else { // contentType = Optional.ofNullable(contentType).orElse(Response.Status.OK); // } // // ResponseSurrogate<T> surrogate = new ResponseSurrogate<>(content, contentType, notification); // return Response.status(status).type(mediaType).entity(surrogate).build(); // } // // public static <T> Response of(T content) { // return of(null, null, content, null, null); // } // // public static <T> Response of(T content, Notification notification) { // return of(null, null, content, null, notification); // } // // public static <T> Response of(Response.Status status, T content, Notification notification) { // return of(status, null, content, null, notification); // } // // public static <T> Response of(T content, MediaType mediaType) { // return of(null, mediaType, content, null, null); // } // // public static <T> Response of(Response.Status status, T content, MediaType mediaType) { // return of(status, mediaType, content, null, null); // } // // public static <T> Response created(T content) { // return created(content, null); // } // // public static <T> Response created(T content, Notification notification) { // return of(Response.Status.CREATED, null, content, null, notification); // } // // public static <T> Response updated(T content) { // return updated(content, null); // } // // public static <T> Response updated(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // public static <T> Response deleted(T content) { // return deleted(content, null); // } // // public static <T> Response deleted(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // }
import info.interactivesystems.gamificationengine.api.ResponseSurrogate; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.api.validation.ResteasyConstraintViolation; import org.jboss.resteasy.api.validation.ResteasyViolationException;
package info.interactivesystems.gamificationengine.api.exeption; @Provider public class ResteasyViolationExceptionMapper implements ExceptionMapper<ResteasyViolationException> { @Override public Response toResponse(ResteasyViolationException ex) { Response.Status status = Response.Status.PRECONDITION_FAILED; List<ResteasyConstraintViolation> constraintViolations = ex.getViolations(); if (ex.getException() != null) { // There are some exceptions during validation throw new RuntimeException(ex.getException()); } Notification notification = new Notification(); constraintViolations.forEach(c -> notification.addError(c.getValue() + ": " + c.getMessage()));
// Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java // public class ResponseSurrogate<T> { // // @SuppressWarnings("FieldCanBeLocal") // // @JsonUnwrapped // @JsonProperty // final T content; // // @JsonProperty // final Response.Status contentResponseType; // // @SuppressWarnings("FieldCanBeLocal") // @JsonProperty // final List<ErrorMessage> info; // // private ResponseSurrogate(T content, Response.Status contentResponseType, Notification info) { // this.content = content; // this.contentResponseType = contentResponseType; // this.info = info.getErrors(); // } // // public static <T> Response of(Response.Status status, MediaType mediaType, T content, Response.Status contentType, Notification notification) { // status = Optional.ofNullable(status).orElse(Response.Status.OK); // mediaType = Optional.ofNullable(mediaType).orElse(MediaType.APPLICATION_JSON_TYPE); // // notification = Optional.ofNullable(notification).orElse(new Notification()); // // if (content == null) { // contentType = Response.Status.BAD_REQUEST; // } else { // contentType = Optional.ofNullable(contentType).orElse(Response.Status.OK); // } // // ResponseSurrogate<T> surrogate = new ResponseSurrogate<>(content, contentType, notification); // return Response.status(status).type(mediaType).entity(surrogate).build(); // } // // public static <T> Response of(T content) { // return of(null, null, content, null, null); // } // // public static <T> Response of(T content, Notification notification) { // return of(null, null, content, null, notification); // } // // public static <T> Response of(Response.Status status, T content, Notification notification) { // return of(status, null, content, null, notification); // } // // public static <T> Response of(T content, MediaType mediaType) { // return of(null, mediaType, content, null, null); // } // // public static <T> Response of(Response.Status status, T content, MediaType mediaType) { // return of(status, mediaType, content, null, null); // } // // public static <T> Response created(T content) { // return created(content, null); // } // // public static <T> Response created(T content, Notification notification) { // return of(Response.Status.CREATED, null, content, null, notification); // } // // public static <T> Response updated(T content) { // return updated(content, null); // } // // public static <T> Response updated(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // public static <T> Response deleted(T content) { // return deleted(content, null); // } // // public static <T> Response deleted(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ResteasyViolationExceptionMapper.java import info.interactivesystems.gamificationengine.api.ResponseSurrogate; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.api.validation.ResteasyConstraintViolation; import org.jboss.resteasy.api.validation.ResteasyViolationException; package info.interactivesystems.gamificationengine.api.exeption; @Provider public class ResteasyViolationExceptionMapper implements ExceptionMapper<ResteasyViolationException> { @Override public Response toResponse(ResteasyViolationException ex) { Response.Status status = Response.Status.PRECONDITION_FAILED; List<ResteasyConstraintViolation> constraintViolations = ex.getViolations(); if (ex.getException() != null) { // There are some exceptions during validation throw new RuntimeException(ex.getException()); } Notification notification = new Notification(); constraintViolations.forEach(c -> notification.addError(c.getValue() + ": " + c.getMessage()));
return ResponseSurrogate.of(status, null, notification);
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/dao/PlayerLevelDAO.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/PlayerLevel.java // @Entity // @JsonIgnoreProperties({ "belongsTo" }) // public class PlayerLevel { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private int levelIndex; // // @NotNull // private String levelName; // // /** // * Gets the id of the player level. // * // * @return The player level's id as int. // */ // public int getId() { // return id; // } // // /** // * Sets the id of a player level. // * // * @param id // * The id of the player level henceforth. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation which the player level belongs to. // * // * @return The organisations object the player level belongs to. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation which the level belongs to and in which a player can // * award it. // * // * @param belongsTo // * The organisation to which the group belongs to henceforth. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * Gets the level's index. // * // * @return The index of the level as an int. // */ // public int getLevelIndex() { // return levelIndex; // } // // /** // * Sets the index of the level. // * // * @param levelIndex // * The index of the level as int. // */ // public void setLevelIndex(int levelIndex) { // this.levelIndex = levelIndex; // } // // /** // * Gets the name of the level. This could be for example a number or a status // * like a title. // * // * @return The name of the level as String. // */ // public String getLevelName() { // return levelName; // } // // /** // * Sets the name of the level. This could be for example a number or a status // * like a title. // * // * @param levelName // * The name of the level henceforth. // */ // public void setLevelName(String levelName) { // this.levelName = levelName; // } // // }
import info.interactivesystems.gamificationengine.entities.PlayerLevel; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query;
package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class PlayerLevelDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new player level in the data base. * * @param pLevel * The player level which should be stored in the data base. * @return The generated id of the player level. */
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/PlayerLevel.java // @Entity // @JsonIgnoreProperties({ "belongsTo" }) // public class PlayerLevel { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private int levelIndex; // // @NotNull // private String levelName; // // /** // * Gets the id of the player level. // * // * @return The player level's id as int. // */ // public int getId() { // return id; // } // // /** // * Sets the id of a player level. // * // * @param id // * The id of the player level henceforth. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation which the player level belongs to. // * // * @return The organisations object the player level belongs to. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation which the level belongs to and in which a player can // * award it. // * // * @param belongsTo // * The organisation to which the group belongs to henceforth. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * Gets the level's index. // * // * @return The index of the level as an int. // */ // public int getLevelIndex() { // return levelIndex; // } // // /** // * Sets the index of the level. // * // * @param levelIndex // * The index of the level as int. // */ // public void setLevelIndex(int levelIndex) { // this.levelIndex = levelIndex; // } // // /** // * Gets the name of the level. This could be for example a number or a status // * like a title. // * // * @return The name of the level as String. // */ // public String getLevelName() { // return levelName; // } // // /** // * Sets the name of the level. This could be for example a number or a status // * like a title. // * // * @param levelName // * The name of the level henceforth. // */ // public void setLevelName(String levelName) { // this.levelName = levelName; // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/dao/PlayerLevelDAO.java import info.interactivesystems.gamificationengine.entities.PlayerLevel; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class PlayerLevelDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new player level in the data base. * * @param pLevel * The player level which should be stored in the data base. * @return The generated id of the player level. */
public int insertPlayerLevel(PlayerLevel pLevel) {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ErrorMessage.java // public class ErrorMessage implements Serializable { // // private static final long serialVersionUID = 9039774438272543442L; // // private CharSequence message; // // public static ErrorMessage of(CharSequence message) { // ErrorMessage errorMessage = new ErrorMessage(); // errorMessage.setMessage(message); // return errorMessage; // } // // public void setMessage(CharSequence message) { // this.message = message; // } // // public CharSequence getMessage() { // return message; // } // } // // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/Notification.java // public class Notification { // // private final List<ErrorMessage> errors = new ArrayList<>(); // // public static Notification of(CharSequence... messages) { // Notification notification = new Notification(); // Stream.of(messages).forEach(notification::addError); // return notification; // } // // public void addError(CharSequence message) { // errors.add(ErrorMessage.of(message)); // } // // public List<ErrorMessage> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // }
import info.interactivesystems.gamificationengine.api.exeption.ErrorMessage; import info.interactivesystems.gamificationengine.api.exeption.Notification; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.annotation.JsonProperty;
package info.interactivesystems.gamificationengine.api; /** * This surrogate is used to add to each returned object an error field. The * error field may contain a list of errors. The deputized object is unwrapped, * so it seems the error field exists in any response object. * * @param <T> */ public class ResponseSurrogate<T> { @SuppressWarnings("FieldCanBeLocal") // @JsonUnwrapped @JsonProperty final T content; @JsonProperty final Response.Status contentResponseType; @SuppressWarnings("FieldCanBeLocal") @JsonProperty
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ErrorMessage.java // public class ErrorMessage implements Serializable { // // private static final long serialVersionUID = 9039774438272543442L; // // private CharSequence message; // // public static ErrorMessage of(CharSequence message) { // ErrorMessage errorMessage = new ErrorMessage(); // errorMessage.setMessage(message); // return errorMessage; // } // // public void setMessage(CharSequence message) { // this.message = message; // } // // public CharSequence getMessage() { // return message; // } // } // // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/Notification.java // public class Notification { // // private final List<ErrorMessage> errors = new ArrayList<>(); // // public static Notification of(CharSequence... messages) { // Notification notification = new Notification(); // Stream.of(messages).forEach(notification::addError); // return notification; // } // // public void addError(CharSequence message) { // errors.add(ErrorMessage.of(message)); // } // // public List<ErrorMessage> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java import info.interactivesystems.gamificationengine.api.exeption.ErrorMessage; import info.interactivesystems.gamificationengine.api.exeption.Notification; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.annotation.JsonProperty; package info.interactivesystems.gamificationengine.api; /** * This surrogate is used to add to each returned object an error field. The * error field may contain a list of errors. The deputized object is unwrapped, * so it seems the error field exists in any response object. * * @param <T> */ public class ResponseSurrogate<T> { @SuppressWarnings("FieldCanBeLocal") // @JsonUnwrapped @JsonProperty final T content; @JsonProperty final Response.Status contentResponseType; @SuppressWarnings("FieldCanBeLocal") @JsonProperty
final List<ErrorMessage> info;
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ErrorMessage.java // public class ErrorMessage implements Serializable { // // private static final long serialVersionUID = 9039774438272543442L; // // private CharSequence message; // // public static ErrorMessage of(CharSequence message) { // ErrorMessage errorMessage = new ErrorMessage(); // errorMessage.setMessage(message); // return errorMessage; // } // // public void setMessage(CharSequence message) { // this.message = message; // } // // public CharSequence getMessage() { // return message; // } // } // // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/Notification.java // public class Notification { // // private final List<ErrorMessage> errors = new ArrayList<>(); // // public static Notification of(CharSequence... messages) { // Notification notification = new Notification(); // Stream.of(messages).forEach(notification::addError); // return notification; // } // // public void addError(CharSequence message) { // errors.add(ErrorMessage.of(message)); // } // // public List<ErrorMessage> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // }
import info.interactivesystems.gamificationengine.api.exeption.ErrorMessage; import info.interactivesystems.gamificationengine.api.exeption.Notification; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.annotation.JsonProperty;
package info.interactivesystems.gamificationengine.api; /** * This surrogate is used to add to each returned object an error field. The * error field may contain a list of errors. The deputized object is unwrapped, * so it seems the error field exists in any response object. * * @param <T> */ public class ResponseSurrogate<T> { @SuppressWarnings("FieldCanBeLocal") // @JsonUnwrapped @JsonProperty final T content; @JsonProperty final Response.Status contentResponseType; @SuppressWarnings("FieldCanBeLocal") @JsonProperty final List<ErrorMessage> info;
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ErrorMessage.java // public class ErrorMessage implements Serializable { // // private static final long serialVersionUID = 9039774438272543442L; // // private CharSequence message; // // public static ErrorMessage of(CharSequence message) { // ErrorMessage errorMessage = new ErrorMessage(); // errorMessage.setMessage(message); // return errorMessage; // } // // public void setMessage(CharSequence message) { // this.message = message; // } // // public CharSequence getMessage() { // return message; // } // } // // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/Notification.java // public class Notification { // // private final List<ErrorMessage> errors = new ArrayList<>(); // // public static Notification of(CharSequence... messages) { // Notification notification = new Notification(); // Stream.of(messages).forEach(notification::addError); // return notification; // } // // public void addError(CharSequence message) { // errors.add(ErrorMessage.of(message)); // } // // public List<ErrorMessage> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java import info.interactivesystems.gamificationengine.api.exeption.ErrorMessage; import info.interactivesystems.gamificationengine.api.exeption.Notification; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.annotation.JsonProperty; package info.interactivesystems.gamificationengine.api; /** * This surrogate is used to add to each returned object an error field. The * error field may contain a list of errors. The deputized object is unwrapped, * so it seems the error field exists in any response object. * * @param <T> */ public class ResponseSurrogate<T> { @SuppressWarnings("FieldCanBeLocal") // @JsonUnwrapped @JsonProperty final T content; @JsonProperty final Response.Status contentResponseType; @SuppressWarnings("FieldCanBeLocal") @JsonProperty final List<ErrorMessage> info;
private ResponseSurrogate(T content, Response.Status contentResponseType, Notification info) {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/validation/ValidApiKey.java
// Path: src/main/java/info/interactivesystems/gamificationengine/dao/OrganisationDAO.java // @Named // @Stateless // public class OrganisationDAO { // // @PersistenceContext(unitName = PersistenceUnit.PROJECT) // private EntityManager em; // // /** // * Stores a new organisation in the data base. // * // * @param organisation // * The {@link Organisation} that should be stored in the data base. // */ // public void insertOrganisation(Organisation organisation) { // em.persist(organisation); // } // // /** // * Gets the organisation from the data base. // * // * @param id // * The id of the requsted organisaiton. // * @return The {@link Organisation} that is associated with the passed id. // */ // public Organisation getOrganisation(int id) { // Query query = em.createQuery("select o from Organisation o where o.id=:id", Organisation.class); // query.setParameter("id", id); // List list = query.getResultList(); // if (list.isEmpty()) { // return null; // } // return ((Organisation) list.get(0)); // } // // /** // * Gets all organisations which belong to an email address. // * // * @param email // * The email address of the requested organisaiton. // * @return The {@link List} of {@link Organisation}s that are associated with the passed email address. // */ // public List<Organisation> getAllOrganisations(String email) { // Query query = em.createQuery("select entity from Organisation entity join entity.managers m where m.email=:email"); // query.setParameter("email", email); // // List list = query.getResultList(); // if (list.isEmpty()) { // return null; // } // // return list; // } // // /** // * Gets all organisations which are associated with the specific API key. The result // * should only be one organisation. // * // * @param apiKey // * The API key to which the organisation belongs to. // * @return A {@link List} of {@link Organisation}s that are associated to the passed // * API key. // */ // public Organisation getOrganisationByApiKey(String apiKey) { // Query query = em.createQuery("select entity from Organisation entity where entity.apiKey=:apiKey"); // query.setParameter("apiKey", apiKey); // // List list = query.getResultList(); // // if (list.isEmpty()) { // return null; // } // // return ((Organisation) list.get(0)); // } // // /** // * Checks whether the data base contains the passed API key. // * // * @param apiKey // * The API key that is tested. This is represented by a {@link CharSequence} // * or null. // * @return True if the API key exists in data base, if null false is returned. // */ // public boolean checkApiKey(CharSequence apiKey) { // if (apiKey != null) { // try { // Query query = em.createQuery("select entity from Organisation entity where entity.apiKey=:apiKey"); // query.setParameter("apiKey", apiKey); // return query.getSingleResult() != null; // } catch (NoResultException e) { // // don't care // } // } // return false; // } // }
import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import info.interactivesystems.gamificationengine.dao.OrganisationDAO; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Inject; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload;
package info.interactivesystems.gamificationengine.api.validation; /** * The annotated {@code CharSequence} will be checked for existence in the * data base. * * Note: {@code null} elements are considered as invalid. */ @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = ValidApiKey.ApiKeyValidator.class) @Documented public @interface ValidApiKey { public static class ApiKeyValidator implements ConstraintValidator<ValidApiKey, CharSequence> { @Inject
// Path: src/main/java/info/interactivesystems/gamificationengine/dao/OrganisationDAO.java // @Named // @Stateless // public class OrganisationDAO { // // @PersistenceContext(unitName = PersistenceUnit.PROJECT) // private EntityManager em; // // /** // * Stores a new organisation in the data base. // * // * @param organisation // * The {@link Organisation} that should be stored in the data base. // */ // public void insertOrganisation(Organisation organisation) { // em.persist(organisation); // } // // /** // * Gets the organisation from the data base. // * // * @param id // * The id of the requsted organisaiton. // * @return The {@link Organisation} that is associated with the passed id. // */ // public Organisation getOrganisation(int id) { // Query query = em.createQuery("select o from Organisation o where o.id=:id", Organisation.class); // query.setParameter("id", id); // List list = query.getResultList(); // if (list.isEmpty()) { // return null; // } // return ((Organisation) list.get(0)); // } // // /** // * Gets all organisations which belong to an email address. // * // * @param email // * The email address of the requested organisaiton. // * @return The {@link List} of {@link Organisation}s that are associated with the passed email address. // */ // public List<Organisation> getAllOrganisations(String email) { // Query query = em.createQuery("select entity from Organisation entity join entity.managers m where m.email=:email"); // query.setParameter("email", email); // // List list = query.getResultList(); // if (list.isEmpty()) { // return null; // } // // return list; // } // // /** // * Gets all organisations which are associated with the specific API key. The result // * should only be one organisation. // * // * @param apiKey // * The API key to which the organisation belongs to. // * @return A {@link List} of {@link Organisation}s that are associated to the passed // * API key. // */ // public Organisation getOrganisationByApiKey(String apiKey) { // Query query = em.createQuery("select entity from Organisation entity where entity.apiKey=:apiKey"); // query.setParameter("apiKey", apiKey); // // List list = query.getResultList(); // // if (list.isEmpty()) { // return null; // } // // return ((Organisation) list.get(0)); // } // // /** // * Checks whether the data base contains the passed API key. // * // * @param apiKey // * The API key that is tested. This is represented by a {@link CharSequence} // * or null. // * @return True if the API key exists in data base, if null false is returned. // */ // public boolean checkApiKey(CharSequence apiKey) { // if (apiKey != null) { // try { // Query query = em.createQuery("select entity from Organisation entity where entity.apiKey=:apiKey"); // query.setParameter("apiKey", apiKey); // return query.getSingleResult() != null; // } catch (NoResultException e) { // // don't care // } // } // return false; // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/validation/ValidApiKey.java import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import info.interactivesystems.gamificationengine.dao.OrganisationDAO; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Inject; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; package info.interactivesystems.gamificationengine.api.validation; /** * The annotated {@code CharSequence} will be checked for existence in the * data base. * * Note: {@code null} elements are considered as invalid. */ @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = ValidApiKey.ApiKeyValidator.class) @Documented public @interface ValidApiKey { public static class ApiKeyValidator implements ConstraintValidator<ValidApiKey, CharSequence> { @Inject
OrganisationDAO organisationDao;
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/ValidateUtils.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // }
import info.interactivesystems.gamificationengine.api.exeption.ApiError; import javax.ws.rs.core.Response;
package info.interactivesystems.gamificationengine.api; public class ValidateUtils { /** * Validates whether the assigned object is null. * * @param id * The id of the object. This is needed for output. * @param object * The object that is tested. * * @return Validated object identity */ public static <T> T requireNotNull(int id, T object) { if (object == null) {
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/ValidateUtils.java import info.interactivesystems.gamificationengine.api.exeption.ApiError; import javax.ws.rs.core.Response; package info.interactivesystems.gamificationengine.api; public class ValidateUtils { /** * Validates whether the assigned object is null. * * @param id * The id of the object. This is needed for output. * @param object * The object that is tested. * * @return Validated object identity */ public static <T> T requireNotNull(int id, T object) { if (object == null) {
throw new ApiError(Response.Status.NOT_FOUND, "No such id: %s", id);
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/utils/ImageUtils.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // }
import info.interactivesystems.gamificationengine.api.exeption.ApiError; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package info.interactivesystems.gamificationengine.utils; public class ImageUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class); /** * The passed String represents an URL. With this URL a byte[] is created from the image file that was passed as a String that * represents an URL. The format of the image has to be .jpg or .png. Otherwise * an exception is thrown with the hint, that the URL was not valid. * * @param fileLocation * The path an image can be located. This is an URL. * @return byte[] of the image content. */ public static byte[] imageToByte(String fileLocation) { BufferedImage originalImage; byte[] byteImage = null; String format = fileLocation.substring(fileLocation.lastIndexOf(".") + 1); if (format.equals("png") || format.equals("jpg")) { try { URL fileImage = new URL(fileLocation); originalImage = ImageIO.read(fileImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(originalImage, format, baos); byteImage = baos.toByteArray(); } catch (IOException e) {
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/utils/ImageUtils.java import info.interactivesystems.gamificationengine.api.exeption.ApiError; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package info.interactivesystems.gamificationengine.utils; public class ImageUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class); /** * The passed String represents an URL. With this URL a byte[] is created from the image file that was passed as a String that * represents an URL. The format of the image has to be .jpg or .png. Otherwise * an exception is thrown with the hint, that the URL was not valid. * * @param fileLocation * The path an image can be located. This is an URL. * @return byte[] of the image content. */ public static byte[] imageToByte(String fileLocation) { BufferedImage originalImage; byte[] byteImage = null; String format = fileLocation.substring(fileLocation.lastIndexOf(".") + 1); if (format.equals("png") || format.equals("jpg")) { try { URL fileImage = new URL(fileLocation); originalImage = ImageIO.read(fileImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(originalImage, format, baos); byteImage = baos.toByteArray(); } catch (IOException e) {
throw new ApiError(Response.Status.FORBIDDEN, "No valid url was transferred");
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/dao/RoleDAO.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Role.java // @Entity // @JsonIgnoreProperties({ "belongsTo" }) // public class Role implements Serializable { // // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private String name; // // // GETTER & SETTER // /** // * Gets the id of a role. // * // * @return int of the id // */ // public int getId() { // return id; // } // // /** // * Sets the id of a role. // * // * @param id // * The id of the role. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the name of a role. // * // * @return the name of the role as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of a role. // * // * @param name // * The name for a role. // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation which the role belongs to and in which a player can // * have this role. // * // * @return an organisation object. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation which the role belongs to and in which a player can // * have this role. // * // * @param belongsTo // * The organisation object which is associated with the role. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * This method checks if the API key of a role is equal to the organisation's one, which // * means the role belongs to this organisation. If the role's API key is equal to the organiton's one // * it returns true otherwise false. // * // * @param organisation // * The Organisation with thate the API key of the role should be compared. This Organisation // * object may not be null. // * @return boolean // * If both API keys are equal the mehtod return true otherwise false. // */ // public boolean belongsTo(Organisation organisation) { // return getBelongsTo().getApiKey().equals(organisation.getApiKey()); // } // // }
import info.interactivesystems.gamificationengine.entities.Role; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query;
package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class RoleDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new role in the data base. * * @param role * The role which should be stored in the data base. * @return The generated id of the role. */
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/Role.java // @Entity // @JsonIgnoreProperties({ "belongsTo" }) // public class Role implements Serializable { // // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private String name; // // // GETTER & SETTER // /** // * Gets the id of a role. // * // * @return int of the id // */ // public int getId() { // return id; // } // // /** // * Sets the id of a role. // * // * @param id // * The id of the role. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the name of a role. // * // * @return the name of the role as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of a role. // * // * @param name // * The name for a role. // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the organisation which the role belongs to and in which a player can // * have this role. // * // * @return an organisation object. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation which the role belongs to and in which a player can // * have this role. // * // * @param belongsTo // * The organisation object which is associated with the role. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * This method checks if the API key of a role is equal to the organisation's one, which // * means the role belongs to this organisation. If the role's API key is equal to the organiton's one // * it returns true otherwise false. // * // * @param organisation // * The Organisation with thate the API key of the role should be compared. This Organisation // * object may not be null. // * @return boolean // * If both API keys are equal the mehtod return true otherwise false. // */ // public boolean belongsTo(Organisation organisation) { // return getBelongsTo().getApiKey().equals(organisation.getApiKey()); // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/dao/RoleDAO.java import info.interactivesystems.gamificationengine.entities.Role; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class RoleDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new role in the data base. * * @param role * The role which should be stored in the data base. * @return The generated id of the role. */
public int insert(Role role) {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/test/java/info/interactivesystems/gamificationengine/api/ValidateUtilsTest.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // }
import static com.google.common.truth.Truth.assertThat; import info.interactivesystems.gamificationengine.api.exeption.ApiError; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;
package info.interactivesystems.gamificationengine.api; public class ValidateUtilsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testRequireNotNull() { Object object = new Object(); assertThat(ValidateUtils.requireNotNull(0, object)).isNotNull(); } @Test public void testRequireNotNullException() {
// Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java // @ApplicationException // public class ApiError extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // /** // * // * @param status // * a HTTP status code. // * @param message // * a description of the error cause. // */ // public ApiError(Response.Status status, String message) { // this(status, message, new Object[] {}); // } // // /** // * @param status // * a HTTP status code // * @param message // * a description of the error cause, may be a formatted string. // * @param args // * for format string, may be zero, see {@link String#format test} // * . // */ // public ApiError(Response.Status status, String message, Object... args) { // super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args)))); // } // } // Path: src/test/java/info/interactivesystems/gamificationengine/api/ValidateUtilsTest.java import static com.google.common.truth.Truth.assertThat; import info.interactivesystems.gamificationengine.api.exeption.ApiError; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; package info.interactivesystems.gamificationengine.api; public class ValidateUtilsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testRequireNotNull() { Object object = new Object(); assertThat(ValidateUtils.requireNotNull(0, object)).isNotNull(); } @Test public void testRequireNotNullException() {
thrown.expect(ApiError.class);
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/dao/RewardDAO.java
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/rewards/Reward.java // @Entity // @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // @DiscriminatorColumn(name = "REWARD_TYPE", discriminatorType = DiscriminatorType.STRING) // @JsonIgnoreProperties({ "belongsTo", "goals" }) // public abstract class Reward { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private String name; // // private String description; // // private int timeToLive; // // @ManyToMany(fetch = FetchType.EAGER, mappedBy = "rewards") // @JsonManagedReference // private List<Goal> goals; // // public abstract void addReward(Player player, GoalDAO goalDao, RuleDAO ruleDao); // public abstract void addReward(PlayerGroup group, GoalDAO goalDao, RuleDAO ruleDao); // // // /** // * Gets the id of the reward which was generated by the creation. // * // * @return The reward's id as int. // */ // public int getId() { // return id; // } // // /** // * Sets the id of the reward. // * // * @param id // * The id of the reward. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation the reward belongs to. // * // * @return The organisation of the reward as an object. The organisation must not be // * null. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation to which this reward belongs to. // * // * @param belongsTo // * The reward's organisation. This parameter must not be null. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * Gets the information about how long the reward can exist. // * // * @return The value for how long the reward exist. // */ // public int getTimeToLive() { // return timeToLive; // } // // /** // * Sets the information about how long the reward can exist. // * // * @param timeToLive // * Time how long the reward can exist as int. // */ // public void setTimeToLive(int timeToLive) { // this.timeToLive = timeToLive; // } // // /** // * This method tests if a reward belongs to a specific organisation. Therefore // * it is tested if the organisation's API key matchs the reward's API key of the // * assigned organisation. // * // * @param organisation // * The organisation object a reward may belongs to. // * @return // * Boolean value if the API key of the group is the same // * of the tested organisation (true) or not (false). // */ // public boolean belongsTo(Organisation organisation) { // return getBelongsTo().getApiKey().equals(organisation.getApiKey()); // } // // /** // * Gets the description of an achievement. This could contains for example the // * different tasks which have to be completed to get this achievement. // * // * @return the achievement's description // */ // public String getDescription() { // return description; // } // // /** // * Sets the description of an achievement. This contains for example further // * information about how the achievement can be earned, like all requirements to // * get the achievement or the process to award the achievement. // * // * @param description // * of the achievement // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * Gets the name of an achievement which can describe the success in a short // * way and can be displayed in the application. // * // * @return The achievement's name as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an achievement, which can describe the success in a short // * way and can be displayed in the application. // * // * @param name // * The name of the achievement as a String. // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the list of goals to which this reward is assigned. // * // * @return All goals with this reward as List of Goals. // */ // public List<Goal> getGoals() { // return goals; // } // // /** // * Sets the list of goals to which this reward is assigned. // * // * @param goals // * The goals to which this reward should be assigned. // */ // public void setGoals(List<Goal> goals) { // this.goals = goals; // } // }
import info.interactivesystems.gamificationengine.entities.rewards.Reward; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query;
package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class RewardDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new reward in the data base. * * @param reward * The reward which should be stored in the data base. * @return The generated id of the reward. */
// Path: src/main/java/info/interactivesystems/gamificationengine/entities/rewards/Reward.java // @Entity // @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // @DiscriminatorColumn(name = "REWARD_TYPE", discriminatorType = DiscriminatorType.STRING) // @JsonIgnoreProperties({ "belongsTo", "goals" }) // public abstract class Reward { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private int id; // // @NotNull // @ManyToOne // private Organisation belongsTo; // // private String name; // // private String description; // // private int timeToLive; // // @ManyToMany(fetch = FetchType.EAGER, mappedBy = "rewards") // @JsonManagedReference // private List<Goal> goals; // // public abstract void addReward(Player player, GoalDAO goalDao, RuleDAO ruleDao); // public abstract void addReward(PlayerGroup group, GoalDAO goalDao, RuleDAO ruleDao); // // // /** // * Gets the id of the reward which was generated by the creation. // * // * @return The reward's id as int. // */ // public int getId() { // return id; // } // // /** // * Sets the id of the reward. // * // * @param id // * The id of the reward. // */ // public void setId(int id) { // this.id = id; // } // // /** // * Gets the organisation the reward belongs to. // * // * @return The organisation of the reward as an object. The organisation must not be // * null. // */ // public Organisation getBelongsTo() { // return belongsTo; // } // // /** // * Sets the organisation to which this reward belongs to. // * // * @param belongsTo // * The reward's organisation. This parameter must not be null. // */ // public void setBelongsTo(Organisation belongsTo) { // this.belongsTo = belongsTo; // } // // /** // * Gets the information about how long the reward can exist. // * // * @return The value for how long the reward exist. // */ // public int getTimeToLive() { // return timeToLive; // } // // /** // * Sets the information about how long the reward can exist. // * // * @param timeToLive // * Time how long the reward can exist as int. // */ // public void setTimeToLive(int timeToLive) { // this.timeToLive = timeToLive; // } // // /** // * This method tests if a reward belongs to a specific organisation. Therefore // * it is tested if the organisation's API key matchs the reward's API key of the // * assigned organisation. // * // * @param organisation // * The organisation object a reward may belongs to. // * @return // * Boolean value if the API key of the group is the same // * of the tested organisation (true) or not (false). // */ // public boolean belongsTo(Organisation organisation) { // return getBelongsTo().getApiKey().equals(organisation.getApiKey()); // } // // /** // * Gets the description of an achievement. This could contains for example the // * different tasks which have to be completed to get this achievement. // * // * @return the achievement's description // */ // public String getDescription() { // return description; // } // // /** // * Sets the description of an achievement. This contains for example further // * information about how the achievement can be earned, like all requirements to // * get the achievement or the process to award the achievement. // * // * @param description // * of the achievement // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * Gets the name of an achievement which can describe the success in a short // * way and can be displayed in the application. // * // * @return The achievement's name as String. // */ // public String getName() { // return name; // } // // /** // * Sets the name of an achievement, which can describe the success in a short // * way and can be displayed in the application. // * // * @param name // * The name of the achievement as a String. // */ // public void setName(String name) { // this.name = name; // } // // /** // * Gets the list of goals to which this reward is assigned. // * // * @return All goals with this reward as List of Goals. // */ // public List<Goal> getGoals() { // return goals; // } // // /** // * Sets the list of goals to which this reward is assigned. // * // * @param goals // * The goals to which this reward should be assigned. // */ // public void setGoals(List<Goal> goals) { // this.goals = goals; // } // } // Path: src/main/java/info/interactivesystems/gamificationengine/dao/RewardDAO.java import info.interactivesystems.gamificationengine.entities.rewards.Reward; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; package info.interactivesystems.gamificationengine.dao; @Named @Stateless public class RewardDAO { @PersistenceContext(unitName = PersistenceUnit.PROJECT) private EntityManager em; /** * Stores a new reward in the data base. * * @param reward * The reward which should be stored in the data base. * @return The generated id of the reward. */
public int insertReward(Reward reward) {
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java
// Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java // public class ResponseSurrogate<T> { // // @SuppressWarnings("FieldCanBeLocal") // // @JsonUnwrapped // @JsonProperty // final T content; // // @JsonProperty // final Response.Status contentResponseType; // // @SuppressWarnings("FieldCanBeLocal") // @JsonProperty // final List<ErrorMessage> info; // // private ResponseSurrogate(T content, Response.Status contentResponseType, Notification info) { // this.content = content; // this.contentResponseType = contentResponseType; // this.info = info.getErrors(); // } // // public static <T> Response of(Response.Status status, MediaType mediaType, T content, Response.Status contentType, Notification notification) { // status = Optional.ofNullable(status).orElse(Response.Status.OK); // mediaType = Optional.ofNullable(mediaType).orElse(MediaType.APPLICATION_JSON_TYPE); // // notification = Optional.ofNullable(notification).orElse(new Notification()); // // if (content == null) { // contentType = Response.Status.BAD_REQUEST; // } else { // contentType = Optional.ofNullable(contentType).orElse(Response.Status.OK); // } // // ResponseSurrogate<T> surrogate = new ResponseSurrogate<>(content, contentType, notification); // return Response.status(status).type(mediaType).entity(surrogate).build(); // } // // public static <T> Response of(T content) { // return of(null, null, content, null, null); // } // // public static <T> Response of(T content, Notification notification) { // return of(null, null, content, null, notification); // } // // public static <T> Response of(Response.Status status, T content, Notification notification) { // return of(status, null, content, null, notification); // } // // public static <T> Response of(T content, MediaType mediaType) { // return of(null, mediaType, content, null, null); // } // // public static <T> Response of(Response.Status status, T content, MediaType mediaType) { // return of(status, mediaType, content, null, null); // } // // public static <T> Response created(T content) { // return created(content, null); // } // // public static <T> Response created(T content, Notification notification) { // return of(Response.Status.CREATED, null, content, null, notification); // } // // public static <T> Response updated(T content) { // return updated(content, null); // } // // public static <T> Response updated(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // public static <T> Response deleted(T content) { // return deleted(content, null); // } // // public static <T> Response deleted(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // }
import info.interactivesystems.gamificationengine.api.ResponseSurrogate; import javax.ejb.ApplicationException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
package info.interactivesystems.gamificationengine.api.exeption; /** * Application specific exception to provide custom error responses. */ @ApplicationException public class ApiError extends WebApplicationException { private static final long serialVersionUID = 1L; /** * * @param status * a HTTP status code. * @param message * a description of the error cause. */ public ApiError(Response.Status status, String message) { this(status, message, new Object[] {}); } /** * @param status * a HTTP status code * @param message * a description of the error cause, may be a formatted string. * @param args * for format string, may be zero, see {@link String#format test} * . */ public ApiError(Response.Status status, String message, Object... args) {
// Path: src/main/java/info/interactivesystems/gamificationengine/api/ResponseSurrogate.java // public class ResponseSurrogate<T> { // // @SuppressWarnings("FieldCanBeLocal") // // @JsonUnwrapped // @JsonProperty // final T content; // // @JsonProperty // final Response.Status contentResponseType; // // @SuppressWarnings("FieldCanBeLocal") // @JsonProperty // final List<ErrorMessage> info; // // private ResponseSurrogate(T content, Response.Status contentResponseType, Notification info) { // this.content = content; // this.contentResponseType = contentResponseType; // this.info = info.getErrors(); // } // // public static <T> Response of(Response.Status status, MediaType mediaType, T content, Response.Status contentType, Notification notification) { // status = Optional.ofNullable(status).orElse(Response.Status.OK); // mediaType = Optional.ofNullable(mediaType).orElse(MediaType.APPLICATION_JSON_TYPE); // // notification = Optional.ofNullable(notification).orElse(new Notification()); // // if (content == null) { // contentType = Response.Status.BAD_REQUEST; // } else { // contentType = Optional.ofNullable(contentType).orElse(Response.Status.OK); // } // // ResponseSurrogate<T> surrogate = new ResponseSurrogate<>(content, contentType, notification); // return Response.status(status).type(mediaType).entity(surrogate).build(); // } // // public static <T> Response of(T content) { // return of(null, null, content, null, null); // } // // public static <T> Response of(T content, Notification notification) { // return of(null, null, content, null, notification); // } // // public static <T> Response of(Response.Status status, T content, Notification notification) { // return of(status, null, content, null, notification); // } // // public static <T> Response of(T content, MediaType mediaType) { // return of(null, mediaType, content, null, null); // } // // public static <T> Response of(Response.Status status, T content, MediaType mediaType) { // return of(status, mediaType, content, null, null); // } // // public static <T> Response created(T content) { // return created(content, null); // } // // public static <T> Response created(T content, Notification notification) { // return of(Response.Status.CREATED, null, content, null, notification); // } // // public static <T> Response updated(T content) { // return updated(content, null); // } // // public static <T> Response updated(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // public static <T> Response deleted(T content) { // return deleted(content, null); // } // // public static <T> Response deleted(T content, Notification notification) { // return of(Response.Status.OK, null, content, null, notification); // } // // } // Path: src/main/java/info/interactivesystems/gamificationengine/api/exeption/ApiError.java import info.interactivesystems.gamificationengine.api.ResponseSurrogate; import javax.ejb.ApplicationException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; package info.interactivesystems.gamificationengine.api.exeption; /** * Application specific exception to provide custom error responses. */ @ApplicationException public class ApiError extends WebApplicationException { private static final long serialVersionUID = 1L; /** * * @param status * a HTTP status code. * @param message * a description of the error cause. */ public ApiError(Response.Status status, String message) { this(status, message, new Object[] {}); } /** * @param status * a HTTP status code * @param message * a description of the error cause, may be a formatted string. * @param args * for format string, may be zero, see {@link String#format test} * . */ public ApiError(Response.Status status, String message, Object... args) {
super(ResponseSurrogate.of(status, null, Notification.of(String.format(message, args))));
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/git/GitService.java
// Path: src/main/java/org/commonwl/view/researchobject/HashableAgent.java // public class HashableAgent extends Agent { // // private String name; // private URI orcid; // private URI uri; // // public HashableAgent() {} // // public HashableAgent(String name, URI orcid, URI uri) { // this.name = name; // this.orcid = orcid; // this.uri = uri; // } // // @Override // public String getName() { // return name; // } // // @Override // public void setName(String name) { // this.name = name; // } // // @Override // public URI getOrcid() { // return orcid; // } // // @Override // public void setOrcid(URI orcid) { // this.orcid = orcid; // } // // @Override // public URI getUri() { // return uri; // } // // @Override // public void setUri(URI uri) { // this.uri = uri; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass() || super.getClass() != o.getClass()) return false; // // HashableAgent that = (HashableAgent) o; // // // ORCID is a unique identifier so if matches, the objects are equal // if (orcid != null && orcid.equals(that.orcid)) return true; // // // If no ORCID is present but email is the name, the objects are equal // if (orcid == null && uri != null && uri.equals(that.uri)) return true; // // // Default to checking all parameters // if (orcid != null ? !orcid.equals(that.orcid) : that.orcid != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return uri != null ? uri.equals(that.uri) : that.uri == null; // // } // // /** // * ORCID is used as hashcode to fall back to comparison if missing // * @return The hash code for this object // */ // @Override // public int hashCode() { // return orcid != null ? orcid.hashCode() : 0; // } // // }
import org.apache.commons.codec.digest.DigestUtils; import org.commonwl.view.researchobject.HashableAgent; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.RefNotFoundException; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.revwalk.RevCommit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.Set; import static org.apache.jena.ext.com.google.common.io.Files.createTempDir;
throw ex; } } else { throw ex; } } } return repo; } /** * Gets the commit ID of the HEAD for the given repository * @param repo The Git repository * @return The commit ID of the HEAD for the repository * @throws IOException If the HEAD is detached */ public String getCurrentCommitID(Git repo) throws IOException { return repo.getRepository().findRef("HEAD").getObjectId().getName(); } /** * Gets a set of authors for a path in a given repository * @param repo The git repository * @param path The path to get commits for * @return An iterable of commits * @throws GitAPIException Any API errors which may occur * @throws URISyntaxException Error constructing mailto link */
// Path: src/main/java/org/commonwl/view/researchobject/HashableAgent.java // public class HashableAgent extends Agent { // // private String name; // private URI orcid; // private URI uri; // // public HashableAgent() {} // // public HashableAgent(String name, URI orcid, URI uri) { // this.name = name; // this.orcid = orcid; // this.uri = uri; // } // // @Override // public String getName() { // return name; // } // // @Override // public void setName(String name) { // this.name = name; // } // // @Override // public URI getOrcid() { // return orcid; // } // // @Override // public void setOrcid(URI orcid) { // this.orcid = orcid; // } // // @Override // public URI getUri() { // return uri; // } // // @Override // public void setUri(URI uri) { // this.uri = uri; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass() || super.getClass() != o.getClass()) return false; // // HashableAgent that = (HashableAgent) o; // // // ORCID is a unique identifier so if matches, the objects are equal // if (orcid != null && orcid.equals(that.orcid)) return true; // // // If no ORCID is present but email is the name, the objects are equal // if (orcid == null && uri != null && uri.equals(that.uri)) return true; // // // Default to checking all parameters // if (orcid != null ? !orcid.equals(that.orcid) : that.orcid != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return uri != null ? uri.equals(that.uri) : that.uri == null; // // } // // /** // * ORCID is used as hashcode to fall back to comparison if missing // * @return The hash code for this object // */ // @Override // public int hashCode() { // return orcid != null ? orcid.hashCode() : 0; // } // // } // Path: src/main/java/org/commonwl/view/git/GitService.java import org.apache.commons.codec.digest.DigestUtils; import org.commonwl.view.researchobject.HashableAgent; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.RefNotFoundException; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.revwalk.RevCommit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.Set; import static org.apache.jena.ext.com.google.common.io.Files.createTempDir; throw ex; } } else { throw ex; } } } return repo; } /** * Gets the commit ID of the HEAD for the given repository * @param repo The Git repository * @return The commit ID of the HEAD for the repository * @throws IOException If the HEAD is detached */ public String getCurrentCommitID(Git repo) throws IOException { return repo.getRepository().findRef("HEAD").getObjectId().getName(); } /** * Gets a set of authors for a path in a given repository * @param repo The git repository * @param path The path to get commits for * @return An iterable of commits * @throws GitAPIException Any API errors which may occur * @throws URISyntaxException Error constructing mailto link */
public Set<HashableAgent> getAuthors(Git repo, String path) throws GitAPIException, URISyntaxException {
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java
// Path: src/main/java/org/commonwl/view/WebConfig.java // public static enum Format { // // Browser // html(MediaType.TEXT_HTML), // // API // json(MediaType.APPLICATION_JSON), // // RDF // turtle("text/turtle"), jsonld("application/ld+json"), rdfxml("application/rdf+xml"), // // Images // svg("image/svg+xml"), png(MediaType.IMAGE_PNG), dot("text/vnd+graphviz"), // // Archives // zip("application/zip"), ro("application/vnd.wf4ever.robundle+zip"), // // raw redirects // yaml("text/x-yaml"), raw(MediaType.APPLICATION_OCTET_STREAM); // // private final MediaType mediaType; // // Format(MediaType mediaType) { // this.mediaType = mediaType; // } // // Format(String mediaType) { // this.mediaType = parseMediaType(mediaType); // } // // public MediaType mediaType() { // return mediaType; // } // }
import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.commonwl.view.WebConfig.Format; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view.workflow; /** * Exception thrown when multiple workflows exist for the request */ @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) public class MultipleWorkflowsException extends RuntimeException { private final Collection<Workflow> matches; public MultipleWorkflowsException(Workflow match) { this(Collections.singleton(match)); } public MultipleWorkflowsException(Collection<Workflow> matches) { if (matches.isEmpty()) { throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); } this.matches = matches; } // Always CRLF in text/uri-list private final String CRLF = "\r\n"; public String getRawPermalink() { // all raw URIs should be the same without ?part=
// Path: src/main/java/org/commonwl/view/WebConfig.java // public static enum Format { // // Browser // html(MediaType.TEXT_HTML), // // API // json(MediaType.APPLICATION_JSON), // // RDF // turtle("text/turtle"), jsonld("application/ld+json"), rdfxml("application/rdf+xml"), // // Images // svg("image/svg+xml"), png(MediaType.IMAGE_PNG), dot("text/vnd+graphviz"), // // Archives // zip("application/zip"), ro("application/vnd.wf4ever.robundle+zip"), // // raw redirects // yaml("text/x-yaml"), raw(MediaType.APPLICATION_OCTET_STREAM); // // private final MediaType mediaType; // // Format(MediaType mediaType) { // this.mediaType = mediaType; // } // // Format(String mediaType) { // this.mediaType = parseMediaType(mediaType); // } // // public MediaType mediaType() { // return mediaType; // } // } // Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.commonwl.view.WebConfig.Format; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view.workflow; /** * Exception thrown when multiple workflows exist for the request */ @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) public class MultipleWorkflowsException extends RuntimeException { private final Collection<Workflow> matches; public MultipleWorkflowsException(Workflow match) { this(Collections.singleton(match)); } public MultipleWorkflowsException(Collection<Workflow> matches) { if (matches.isEmpty()) { throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); } this.matches = matches; } // Always CRLF in text/uri-list private final String CRLF = "\r\n"; public String getRawPermalink() { // all raw URIs should be the same without ?part=
return matches.stream().findAny().get().getPermalink(Format.raw);
common-workflow-language/cwlviewer
src/test/java/org/commonwl/view/git/GitDetailsTest.java
// Path: src/main/java/org/commonwl/view/git/GitDetails.java // public static String normaliseUrl(String url) { // return url.replace("http://", "") // .replace("https://", "") // .replace("ssh://", "") // .replace("git://", "") // .replace("www.", ""); // }
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import static org.commonwl.view.git.GitDetails.normaliseUrl;
/** * Construct the internal link to a workflow from Git details */ @Test public void getInternalUrl() throws Exception { assertEquals("/workflows/github.com/owner/repoName/blob/branch/path/within/structure.cwl", GITHUB_DETAILS.getInternalUrl()); assertEquals("/workflows/gitlab.com/owner/repoName/blob/branch/path/within/structure.cwl", GITLAB_DETAILS.getInternalUrl()); assertEquals("/workflows/bitbucket.org/owner/repoName.git/branch/path/within/structure.cwl", BITBUCKET_DETAILS.getInternalUrl()); assertEquals("/workflows/could.com/be/anything.git/branch/path/within/structure.cwl", GENERIC_DETAILS.getInternalUrl()); assertEquals("/workflows/could.com/be/anything.git/branch/path/within/structure/packed.cwl#testId", PACKED_DETAILS.getInternalUrl()); } /** * Construct the raw URL to a workflow file from Git details */ @Test public void getRawUrl() throws Exception { assertEquals("https://raw.githubusercontent.com/owner/repoName/branch/path/within/structure.cwl", GITHUB_DETAILS.getRawUrl()); assertEquals("https://gitlab.com/owner/repoName/raw/branch/path/within/structure.cwl", GITLAB_DETAILS.getRawUrl()); assertEquals("https://bitbucket.org/owner/repoName/raw/branch/path/within/structure.cwl", BITBUCKET_DETAILS.getRawUrl()); // No raw URL for generic git repo assertEquals("https://could.com/be/anything.git", GENERIC_DETAILS.getRawUrl()); } /** * Normalise a URL removing protocol and www. */ @Test public void getNormaliseUrl() throws Exception {
// Path: src/main/java/org/commonwl/view/git/GitDetails.java // public static String normaliseUrl(String url) { // return url.replace("http://", "") // .replace("https://", "") // .replace("ssh://", "") // .replace("git://", "") // .replace("www.", ""); // } // Path: src/test/java/org/commonwl/view/git/GitDetailsTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import static org.commonwl.view.git.GitDetails.normaliseUrl; /** * Construct the internal link to a workflow from Git details */ @Test public void getInternalUrl() throws Exception { assertEquals("/workflows/github.com/owner/repoName/blob/branch/path/within/structure.cwl", GITHUB_DETAILS.getInternalUrl()); assertEquals("/workflows/gitlab.com/owner/repoName/blob/branch/path/within/structure.cwl", GITLAB_DETAILS.getInternalUrl()); assertEquals("/workflows/bitbucket.org/owner/repoName.git/branch/path/within/structure.cwl", BITBUCKET_DETAILS.getInternalUrl()); assertEquals("/workflows/could.com/be/anything.git/branch/path/within/structure.cwl", GENERIC_DETAILS.getInternalUrl()); assertEquals("/workflows/could.com/be/anything.git/branch/path/within/structure/packed.cwl#testId", PACKED_DETAILS.getInternalUrl()); } /** * Construct the raw URL to a workflow file from Git details */ @Test public void getRawUrl() throws Exception { assertEquals("https://raw.githubusercontent.com/owner/repoName/branch/path/within/structure.cwl", GITHUB_DETAILS.getRawUrl()); assertEquals("https://gitlab.com/owner/repoName/raw/branch/path/within/structure.cwl", GITLAB_DETAILS.getRawUrl()); assertEquals("https://bitbucket.org/owner/repoName/raw/branch/path/within/structure.cwl", BITBUCKET_DETAILS.getRawUrl()); // No raw URL for generic git repo assertEquals("https://could.com/be/anything.git", GENERIC_DETAILS.getRawUrl()); } /** * Normalise a URL removing protocol and www. */ @Test public void getNormaliseUrl() throws Exception {
assertEquals("github.com/test/url/here", normaliseUrl("https://www.github.com/test/url/here"));
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/cwl/CWLTool.java
// Path: src/main/java/org/commonwl/view/util/StreamGobbler.java // public class StreamGobbler extends Thread { // private final String lineSeparator = System.getProperty("line.separator"); // // private InputStream is; // private String content = ""; // // public StreamGobbler(InputStream is) { // this.is = is; // } // // public void run() { // try { // InputStreamReader isr = new InputStreamReader(is); // BufferedReader br = new BufferedReader(isr); // String line; // while ((line = br.readLine()) != null) { // content += line + lineSeparator; // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // public String getContent() { // return content; // } // }
import org.commonwl.view.util.StreamGobbler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; if ((line = br.readLine()) != null) { cwlToolVersion = line.substring(line.indexOf(' ') + 1); return cwlToolVersion; } else { return "<error getting cwl version>"; } } catch (IOException ex) { return "<error getting cwl version>"; } } /** * Runs cwltool on a workflow with a given argument * @param argument The argument for cwltool * @param workflowUrl The url of the workflow * @return The standard output of cwltool * @throws CWLValidationException Errors from cwltool */ private String runCwltoolOnWorkflow(String argument, String workflowUrl) throws CWLValidationException { try { // Run command String[] command = {"cwltool", "--non-strict", "--quiet", "--skip-schemas", argument, workflowUrl}; ProcessBuilder cwlToolProcess = new ProcessBuilder(command); Process process = cwlToolProcess.start(); // Read output from the process using threads
// Path: src/main/java/org/commonwl/view/util/StreamGobbler.java // public class StreamGobbler extends Thread { // private final String lineSeparator = System.getProperty("line.separator"); // // private InputStream is; // private String content = ""; // // public StreamGobbler(InputStream is) { // this.is = is; // } // // public void run() { // try { // InputStreamReader isr = new InputStreamReader(is); // BufferedReader br = new BufferedReader(isr); // String line; // while ((line = br.readLine()) != null) { // content += line + lineSeparator; // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // public String getContent() { // return content; // } // } // Path: src/main/java/org/commonwl/view/cwl/CWLTool.java import org.commonwl.view.util.StreamGobbler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; if ((line = br.readLine()) != null) { cwlToolVersion = line.substring(line.indexOf(' ') + 1); return cwlToolVersion; } else { return "<error getting cwl version>"; } } catch (IOException ex) { return "<error getting cwl version>"; } } /** * Runs cwltool on a workflow with a given argument * @param argument The argument for cwltool * @param workflowUrl The url of the workflow * @return The standard output of cwltool * @throws CWLValidationException Errors from cwltool */ private String runCwltoolOnWorkflow(String argument, String workflowUrl) throws CWLValidationException { try { // Run command String[] command = {"cwltool", "--non-strict", "--quiet", "--skip-schemas", argument, workflowUrl}; ProcessBuilder cwlToolProcess = new ProcessBuilder(command); Process process = cwlToolProcess.start(); // Read output from the process using threads
StreamGobbler inputGobbler = new StreamGobbler(process.getInputStream());
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/Scheduler.java
// Path: src/main/java/org/commonwl/view/workflow/QueuedWorkflowRepository.java // public interface QueuedWorkflowRepository extends JpaRepository<QueuedWorkflow, String>, QueuedWorkflowRepositoryCustom { // // /** // * Deletes all queued workflows with date retrieved on older or equal to the Date argument passed. // * // * @param retrievedOn Date of when the queued workflow was retrieved // * @return The number of queued workflows deleted // */ // @Transactional // @Modifying // @Query(value = "DELETE FROM queued_workflow q WHERE q.temp_representation ->> 'retrievedOn' <= ?1", nativeQuery = true) // Integer deleteByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn); // // /** // * Finds and returns all queued workflows with date retrieved on older or equal to the Date argument passed. // * // * @param retrievedOn Details of where the queued workflow is from // * @return A list of queued workflows // */ // @Query(value = "SELECT q.* FROM queued_workflow q WHERE q.temp_representation ->> 'retrievedOn' <= ?1", nativeQuery = true) // List<QueuedWorkflow> findByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn); // // }
import org.commonwl.view.workflow.QueuedWorkflowRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date;
package org.commonwl.view; /** * Scheduler class for recurrent processes. */ @Component public class Scheduler { private final Logger logger = LoggerFactory.getLogger(this.getClass());
// Path: src/main/java/org/commonwl/view/workflow/QueuedWorkflowRepository.java // public interface QueuedWorkflowRepository extends JpaRepository<QueuedWorkflow, String>, QueuedWorkflowRepositoryCustom { // // /** // * Deletes all queued workflows with date retrieved on older or equal to the Date argument passed. // * // * @param retrievedOn Date of when the queued workflow was retrieved // * @return The number of queued workflows deleted // */ // @Transactional // @Modifying // @Query(value = "DELETE FROM queued_workflow q WHERE q.temp_representation ->> 'retrievedOn' <= ?1", nativeQuery = true) // Integer deleteByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn); // // /** // * Finds and returns all queued workflows with date retrieved on older or equal to the Date argument passed. // * // * @param retrievedOn Details of where the queued workflow is from // * @return A list of queued workflows // */ // @Query(value = "SELECT q.* FROM queued_workflow q WHERE q.temp_representation ->> 'retrievedOn' <= ?1", nativeQuery = true) // List<QueuedWorkflow> findByTempRepresentation_RetrievedOnLessThanEqual(Date retrievedOn); // // } // Path: src/main/java/org/commonwl/view/Scheduler.java import org.commonwl.view.workflow.QueuedWorkflowRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; package org.commonwl.view; /** * Scheduler class for recurrent processes. */ @Component public class Scheduler { private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final QueuedWorkflowRepository queuedWorkflowRepository;
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // }
import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // } // Path: src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */
@ExceptionHandler(WorkflowNotFoundException.class)
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // }
import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */ @ExceptionHandler(WorkflowNotFoundException.class) public ResponseEntity<?> handleNotFound() { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>("Workflow or git commit could not be found", headers, HttpStatus.NOT_FOUND); } /** * More than one workflow (or workflow parts) found * * @return A text/uri-list of potential representations */
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // } // Path: src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */ @ExceptionHandler(WorkflowNotFoundException.class) public ResponseEntity<?> handleNotFound() { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>("Workflow or git commit could not be found", headers, HttpStatus.NOT_FOUND); } /** * More than one workflow (or workflow parts) found * * @return A text/uri-list of potential representations */
@ExceptionHandler(MultipleWorkflowsException.class)
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // }
import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */ @ExceptionHandler(WorkflowNotFoundException.class) public ResponseEntity<?> handleNotFound() { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>("Workflow or git commit could not be found", headers, HttpStatus.NOT_FOUND); } /** * More than one workflow (or workflow parts) found * * @return A text/uri-list of potential representations */ @ExceptionHandler(MultipleWorkflowsException.class) public ResponseEntity<?> handleMultipleWorkflows(MultipleWorkflowsException ex) { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("text/uri-list")); return new ResponseEntity<>(ex.toString(), headers, HttpStatus.MULTIPLE_CHOICES); } /** * Workflow exists but representation is not found eg Generic git workflow * asking for raw workflow URL * * @return A plain text error message */
// Path: src/main/java/org/commonwl/view/workflow/MultipleWorkflowsException.java // @ResponseStatus(value = HttpStatus.MULTIPLE_CHOICES) // public class MultipleWorkflowsException extends RuntimeException { // // private final Collection<Workflow> matches; // // public MultipleWorkflowsException(Workflow match) { // this(Collections.singleton(match)); // } // // public MultipleWorkflowsException(Collection<Workflow> matches) { // if (matches.isEmpty()) { // throw new IllegalArgumentException("MultipleWorkflowsException, but empty list of workflows"); // } // this.matches = matches; // } // // // Always CRLF in text/uri-list // private final String CRLF = "\r\n"; // // public String getRawPermalink() { // // all raw URIs should be the same without ?part= // return matches.stream().findAny().get().getPermalink(Format.raw); // } // // /** // * Generate a text/uri-list of potential representations/redirects // * // * @see https://www.iana.org/assignments/media-types/text/uri-list // */ // @Override // public String toString() { // StringBuffer sb = new StringBuffer(); // sb.append("## Multiple workflow representations found"); // sb.append(CRLF); // sb.append("# "); // sb.append(CRLF); // // sb.append("# "); // sb.append(Format.raw.mediaType()); // sb.append(CRLF); // sb.append(getRawPermalink()); // sb.append(CRLF); // // Set<String> seen = new HashSet<>(); // // For each workflow, link to each remaining format // for (Workflow w : matches) { // if (!seen.add(w.getIdentifier())) { // // Skip permalink duplicates // continue; // } // sb.append("#"); // sb.append(CRLF); // sb.append("# "); // sb.append(w.getIdentifier()); // sb.append(CRLF); // for (Format f : Format.values()) { // if (f == Format.raw) { // // Already did that one above // continue; // } // sb.append("# "); // sb.append(f.mediaType()); // sb.append(CRLF); // sb.append(w.getPermalink(f)); // sb.append(CRLF); // } // } // return sb.toString(); // } // // } // // Path: src/main/java/org/commonwl/view/workflow/RepresentationNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) // public class RepresentationNotFoundException extends RuntimeException { // } // // Path: src/main/java/org/commonwl/view/workflow/WorkflowNotFoundException.java // @ResponseStatus(value = HttpStatus.NOT_FOUND) // public class WorkflowNotFoundException extends RuntimeException { // } // Path: src/main/java/org/commonwl/view/GlobalControllerErrorHandling.java import java.util.Collections; import org.commonwl.view.workflow.MultipleWorkflowsException; import org.commonwl.view.workflow.RepresentationNotFoundException; import org.commonwl.view.workflow.WorkflowNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; /** * Handles exception handling across the application. * <p> * Because of Spring Boot's content negotiation these handlers are needed when * the error is returned with an otherwise "non acceptable" content type (e.g. * Accept: image/svg+xml but we have to say 404 Not Found) * */ @ControllerAdvice public class GlobalControllerErrorHandling { /** * Workflow can not be found * @return A plain text error message */ @ExceptionHandler(WorkflowNotFoundException.class) public ResponseEntity<?> handleNotFound() { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>("Workflow or git commit could not be found", headers, HttpStatus.NOT_FOUND); } /** * More than one workflow (or workflow parts) found * * @return A text/uri-list of potential representations */ @ExceptionHandler(MultipleWorkflowsException.class) public ResponseEntity<?> handleMultipleWorkflows(MultipleWorkflowsException ex) { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("text/uri-list")); return new ResponseEntity<>(ex.toString(), headers, HttpStatus.MULTIPLE_CHOICES); } /** * Workflow exists but representation is not found eg Generic git workflow * asking for raw workflow URL * * @return A plain text error message */
@ExceptionHandler(RepresentationNotFoundException.class)
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/workflow/QueuedWorkflow.java
// Path: src/main/java/org/commonwl/view/cwl/CWLToolStatus.java // public enum CWLToolStatus { // DOWNLOADING, // RUNNING, // ERROR, // SUCCESS // } // // Path: src/main/java/org/commonwl/view/util/BaseEntity.java // @TypeDefs({ // @TypeDef(name = "json", typeClass = JsonBinaryType.class) // }) // @MappedSuperclass // public class BaseEntity { // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.commonwl.view.cwl.CWLToolStatus; import org.commonwl.view.util.BaseEntity; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; import java.util.Objects;
package org.commonwl.view.workflow; /** * A workflow pending completion of cwltool */ @JsonIgnoreProperties(value = {"id", "tempRepresentation", "workflowList"}) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Entity @Table(name = "queued_workflow") @SuppressWarnings("JpaAttributeTypeInspection")
// Path: src/main/java/org/commonwl/view/cwl/CWLToolStatus.java // public enum CWLToolStatus { // DOWNLOADING, // RUNNING, // ERROR, // SUCCESS // } // // Path: src/main/java/org/commonwl/view/util/BaseEntity.java // @TypeDefs({ // @TypeDef(name = "json", typeClass = JsonBinaryType.class) // }) // @MappedSuperclass // public class BaseEntity { // } // Path: src/main/java/org/commonwl/view/workflow/QueuedWorkflow.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.commonwl.view.cwl.CWLToolStatus; import org.commonwl.view.util.BaseEntity; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; import java.util.Objects; package org.commonwl.view.workflow; /** * A workflow pending completion of cwltool */ @JsonIgnoreProperties(value = {"id", "tempRepresentation", "workflowList"}) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Entity @Table(name = "queued_workflow") @SuppressWarnings("JpaAttributeTypeInspection")
public class QueuedWorkflow extends BaseEntity implements Serializable {
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/workflow/QueuedWorkflow.java
// Path: src/main/java/org/commonwl/view/cwl/CWLToolStatus.java // public enum CWLToolStatus { // DOWNLOADING, // RUNNING, // ERROR, // SUCCESS // } // // Path: src/main/java/org/commonwl/view/util/BaseEntity.java // @TypeDefs({ // @TypeDef(name = "json", typeClass = JsonBinaryType.class) // }) // @MappedSuperclass // public class BaseEntity { // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.commonwl.view.cwl.CWLToolStatus; import org.commonwl.view.util.BaseEntity; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; import java.util.Objects;
package org.commonwl.view.workflow; /** * A workflow pending completion of cwltool */ @JsonIgnoreProperties(value = {"id", "tempRepresentation", "workflowList"}) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Entity @Table(name = "queued_workflow") @SuppressWarnings("JpaAttributeTypeInspection") public class QueuedWorkflow extends BaseEntity implements Serializable { // ID for database @Id @GenericGenerator(name = "uuid2", strategy = "uuid2") @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "uuid2") @Column(length = 36, nullable = false, updatable = false) public String id; // Very barebones workflow to build loading thumbnail and overview @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true) private Workflow tempRepresentation; // List of packed workflows for packed workflows // TODO: Refactor so this is not necessary @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true) private List<WorkflowOverview> workflowList; // Cwltool details @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true)
// Path: src/main/java/org/commonwl/view/cwl/CWLToolStatus.java // public enum CWLToolStatus { // DOWNLOADING, // RUNNING, // ERROR, // SUCCESS // } // // Path: src/main/java/org/commonwl/view/util/BaseEntity.java // @TypeDefs({ // @TypeDef(name = "json", typeClass = JsonBinaryType.class) // }) // @MappedSuperclass // public class BaseEntity { // } // Path: src/main/java/org/commonwl/view/workflow/QueuedWorkflow.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.commonwl.view.cwl.CWLToolStatus; import org.commonwl.view.util.BaseEntity; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; import java.util.Objects; package org.commonwl.view.workflow; /** * A workflow pending completion of cwltool */ @JsonIgnoreProperties(value = {"id", "tempRepresentation", "workflowList"}) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Entity @Table(name = "queued_workflow") @SuppressWarnings("JpaAttributeTypeInspection") public class QueuedWorkflow extends BaseEntity implements Serializable { // ID for database @Id @GenericGenerator(name = "uuid2", strategy = "uuid2") @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "uuid2") @Column(length = 36, nullable = false, updatable = false) public String id; // Very barebones workflow to build loading thumbnail and overview @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true) private Workflow tempRepresentation; // List of packed workflows for packed workflows // TODO: Refactor so this is not necessary @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true) private List<WorkflowOverview> workflowList; // Cwltool details @Column(columnDefinition = "jsonb") @Type(type = "json") @Convert(disableConversion = true)
private CWLToolStatus cwltoolStatus = CWLToolStatus.RUNNING;
common-workflow-language/cwlviewer
src/main/java/org/commonwl/view/PageController.java
// Path: src/main/java/org/commonwl/view/workflow/WorkflowForm.java // public class WorkflowForm { // // private String url; // private String branch; // private String path; // private String packedId; // // public WorkflowForm() {} // // public WorkflowForm(String url) { // setUrl(url); // } // // public WorkflowForm(String url, String branch, String path) { // setUrl(url); // this.branch = branch; // this.path = path; // } // // public WorkflowForm(String url, String branch, String path, String packedId) { // setUrl(url); // this.branch = branch; // this.path = path; // this.packedId = packedId; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // if (url != null) { // this.url = trimTrailingSlashes(url); // } // } // // public String getBranch() { // return branch; // } // // public void setBranch(String branch) { // this.branch = branch; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getPackedId() { // return packedId; // } // // public void setPackedId(String packedId) { // this.packedId = packedId; // } // // /** // * Cuts any trailing slashes off a string // * @param url The string to cut the slashes off // * @return The same string without trailing slashes // */ // private String trimTrailingSlashes(String url) { // return url.replaceAll("\\/+$", ""); // } // // @Override // public String toString() { // return "WorkflowForm [" + (url != null ? "url=" + url + ", " : "") // + (branch != null ? "branch=" + branch + ", " : "") + (path != null ? "path=" + path : "") + "]"; // } // // }
import org.commonwl.view.workflow.WorkflowForm; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; @Controller public class PageController { /** * Main page of the application * @param model The model for the home page where the workflow form is added * @return The view for this page */ @GetMapping("/") public String homePage(Model model, @RequestParam(value = "url", required = false) String defaultURL) {
// Path: src/main/java/org/commonwl/view/workflow/WorkflowForm.java // public class WorkflowForm { // // private String url; // private String branch; // private String path; // private String packedId; // // public WorkflowForm() {} // // public WorkflowForm(String url) { // setUrl(url); // } // // public WorkflowForm(String url, String branch, String path) { // setUrl(url); // this.branch = branch; // this.path = path; // } // // public WorkflowForm(String url, String branch, String path, String packedId) { // setUrl(url); // this.branch = branch; // this.path = path; // this.packedId = packedId; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // if (url != null) { // this.url = trimTrailingSlashes(url); // } // } // // public String getBranch() { // return branch; // } // // public void setBranch(String branch) { // this.branch = branch; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getPackedId() { // return packedId; // } // // public void setPackedId(String packedId) { // this.packedId = packedId; // } // // /** // * Cuts any trailing slashes off a string // * @param url The string to cut the slashes off // * @return The same string without trailing slashes // */ // private String trimTrailingSlashes(String url) { // return url.replaceAll("\\/+$", ""); // } // // @Override // public String toString() { // return "WorkflowForm [" + (url != null ? "url=" + url + ", " : "") // + (branch != null ? "branch=" + branch + ", " : "") + (path != null ? "path=" + path : "") + "]"; // } // // } // Path: src/main/java/org/commonwl/view/PageController.java import org.commonwl.view.workflow.WorkflowForm; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.commonwl.view; @Controller public class PageController { /** * Main page of the application * @param model The model for the home page where the workflow form is added * @return The view for this page */ @GetMapping("/") public String homePage(Model model, @RequestParam(value = "url", required = false) String defaultURL) {
model.addAttribute("workflowForm", new WorkflowForm(defaultURL));
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import fj.Unit; import fj.control.db.DB; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER;
package com.novarto.sanedbc.core.ops; /** * A db operation which takes no parameters, and returns nothing. One usecase for this is executing DDL */ public class EffectOp extends DB<Unit> { private final UpdateOp op; public EffectOp(String sql) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java import fj.Unit; import fj.control.db.DB; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; package com.novarto.sanedbc.core.ops; /** * A db operation which takes no parameters, and returns nothing. One usecase for this is executing DDL */ public class EffectOp extends DB<Unit> { private final UpdateOp op; public EffectOp(String sql) {
this.op = new UpdateOp(sql, NO_BINDER);
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.core.interpreter; public class ValidationDbInterpreterTest { private static final ValidationDbInterpreter DB = new ValidationDbInterpreter( () -> DriverManager.getConnection("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "")); @BeforeClass public static void setupSuite() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.core.interpreter; public class ValidationDbInterpreterTest { private static final ValidationDbInterpreter DB = new ValidationDbInterpreter( () -> DriverManager.getConnection("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "")); @BeforeClass public static void setupSuite() {
DB.transact(new EffectOp("CREATE TABLE BAR (BAZ VARCHAR(100))")).f();
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
insert("a").run(c); insert("b").run(c); throw ex; } }).f(), is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; insert("a").run(c); insert("b").run(c); throw ex; } }).f(), is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) {
return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
return new SelectOp.FjList<>("SELECT * FROM BAR", NO_BINDER, rs -> rs.getString(1));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreterTest.java import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static fj.data.Validation.fail; import static fj.data.Validation.success; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; is(fail(ex)) ); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); SQLException noConn = new SQLException("no connection"); ValidationDbInterpreter noConnection = new ValidationDbInterpreter(() -> { throw noConn; }); assertThat(noConnection.transact(insert("alabala")).f(), is(fail(noConn))); assertThat(DB.submit(selectAll()).f(), is(success(single("x")))); assertThat( DB.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit())).f(), is(success(Unit.unit())) ); assertThat(DB.submit(selectAll()).f(), is(success(arrayList("x", "y", "z")))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
return new SelectOp.FjList<>("SELECT * FROM BAR", NO_BINDER, rs -> rs.getString(1));
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/EffectivelyImmutable.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // }
import com.novarto.lang.Collections; import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.P2; import fj.control.db.DB; import fj.data.Tree; import org.junit.Test; import java.sql.DriverManager; import java.util.List; import java.util.Map; import static fj.P.p; import static fj.data.List.arrayList; import static fj.data.Tree.leaf; import static fj.data.Tree.node; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
//the final result is an immutable data structure. //the intermediate representation was an implementation detail, which is not observable outside this method. //this technique is dubbed "Effectively immutable" return result; } private <A> Tree<A> toTree(A root, Map<A, ? extends Iterable<A>> map) { Iterable<A> theseChildren = map.get(root); if (theseChildren == null || Collections.isEmpty(theseChildren)) { return leaf(root); } fj.data.List.Buffer<Tree<A>> childNodes = fj.data.List.Buffer.empty(); for (A child : theseChildren) { childNodes = childNodes.snoc(toTree(child, map)); } return node(root, childNodes.toList()); } @Test public void testIt() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/EffectivelyImmutable.java import com.novarto.lang.Collections; import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.P2; import fj.control.db.DB; import fj.data.Tree; import org.junit.Test; import java.sql.DriverManager; import java.util.List; import java.util.Map; import static fj.P.p; import static fj.data.List.arrayList; import static fj.data.Tree.leaf; import static fj.data.Tree.node; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; //the final result is an immutable data structure. //the intermediate representation was an implementation detail, which is not observable outside this method. //this technique is dubbed "Effectively immutable" return result; } private <A> Tree<A> toTree(A root, Map<A, ? extends Iterable<A>> map) { Iterable<A> theseChildren = map.get(root); if (theseChildren == null || Collections.isEmpty(theseChildren)) { return leaf(root); } fj.data.List.Buffer<Tree<A>> childNodes = fj.data.List.Buffer.empty(); for (A child : theseChildren) { childNodes = childNodes.snoc(toTree(child, map)); } return node(root, childNodes.toList()); } @Test public void testIt() {
SyncDbInterpreter dbi = new SyncDbInterpreter(
novarto-oss/sane-dbc
sane-dbc-netty/src/test/java/com/novarto/sanedbc/netty/SanityTest.java
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // }
import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.netty; public class SanityTest { private static FutureInterpreter dbAsync; private static HikariDataSource ds; private static UnorderedThreadPoolEventExecutor ex; @BeforeClass public static void setupHikari() {
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // Path: sane-dbc-netty/src/test/java/com/novarto/sanedbc/netty/SanityTest.java import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.netty; public class SanityTest { private static FutureInterpreter dbAsync; private static HikariDataSource ds; private static UnorderedThreadPoolEventExecutor ex; @BeforeClass public static void setupHikari() {
ds = Hikari.createHikari("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "", new Properties());
novarto-oss/sane-dbc
sane-dbc-netty/src/test/java/com/novarto/sanedbc/netty/SanityTest.java
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // }
import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
{ assertThat(c, is(notNullValue())); throw ex; })); assertThat(awaitAndGet(success), is(42)); assertThat(awaitAndGetFailure(fail), is(ex)); } private static <A> A awaitAndGet(Future<A> success) { return tryTo(() -> success.get()); } private static Throwable awaitAndGetFailure(Future<?> failure) { Throwable result = tryTo(failure::await).cause(); if (result == null) { throw new IllegalStateException("expected throwable, got: " + failure.getNow()); } return result; } @AfterClass public static void shutdownHikari() {
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // Path: sane-dbc-netty/src/test/java/com/novarto/sanedbc/netty/SanityTest.java import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; { assertThat(c, is(notNullValue())); throw ex; })); assertThat(awaitAndGet(success), is(42)); assertThat(awaitAndGetFailure(fail), is(ex)); } private static <A> A awaitAndGet(Future<A> success) { return tryTo(() -> success.get()); } private static Throwable awaitAndGetFailure(Future<?> failure) { Throwable result = tryTo(failure::await).cause(); if (result == null) { throw new IllegalStateException("expected throwable, got: " + failure.getNow()); } return result; } @AfterClass public static void shutdownHikari() {
gracefulShutdown(ex, ds);
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/flyway/V1_2__AlterFoo.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // }
import com.novarto.sanedbc.core.ops.UpdateOp; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import java.sql.Connection;
package com.novarto.sanedbc.examples.flyway; /** * Simple migration that inserts a new row in FOO table * * @see JdbcMigration */ @SuppressWarnings("checkstyle:TypeName") public class V1_2__AlterFoo implements JdbcMigration { @Override public void migrate(Connection c) throws Exception {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/flyway/V1_2__AlterFoo.java import com.novarto.sanedbc.core.ops.UpdateOp; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import java.sql.Connection; package com.novarto.sanedbc.examples.flyway; /** * Simple migration that inserts a new row in FOO table * * @see JdbcMigration */ @SuppressWarnings("checkstyle:TypeName") public class V1_2__AlterFoo implements JdbcMigration { @Override public void migrate(Connection c) throws Exception {
new UpdateOp("INSERT INTO FLYWAY.FOO (DESCRIPTION) VALUES (?)", ps -> ps.setString(1, "description 3")).run(c);
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public final class DbOps // { // // private DbOps() // { // throw new UnsupportedOperationException(); // } // // /** // * Given an existing {@link DB<Iterable<A>>}, converts it to an operation that either returns one result, none at all, // * or throws if there is more than one result in the result set. // * // * This is useful if you are issuing a query by a single primary key. Such a query is never expected to return > 1 results // * (in which case the returned DB will throw upon interpretation), but can return no results (which is expressed in the // * return type) // */ // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // } // // // // public static <A> DB<Integer> toChunks(Iterable<A> xs, F<Iterable<A>, DB<Integer>> getOp, int chunkSize) // { // // return new DB<Integer>() // { // @Override public Integer run(Connection c) throws SQLException // { // Integer result = 0; // // List<List<A>> chunks = chunks(xs, chunkSize); // // for (List<A> chunk : chunks) // { // result += getOp.f(chunk).run(c); // } // // return result; // } // }; // // } // // private static <A> List<List<A>> chunks(Iterable<A> xs, int chunkSize) // { // // if (chunkSize < 1) // { // throw new IllegalArgumentException("chunkSize must be >=1"); // } // // List<List<A>> result = new ArrayList<>(); // List<A> currentList = new ArrayList<>(); // result.add(currentList); // int count = 0; // // for (A x : xs) // { // // if (count >= chunkSize) // { // currentList = new ArrayList<>(); // result.add(currentList); // count = 0; // } // // currentList.add(x); // count++; // // } // // List<A> last = result.get(result.size() - 1); // if (last.size() == 0) // { // result.remove(result.size() - 1); // } // // return result; // } // // /** // * Given an iterable of DB's, convert it to a single DB of iterable. E.g. List[DB[A]] => DB[List[A]]. // * Utilizes a CanBuildFrom instance to construct the result iterable // * @param xs the iterable of DB's to convert // * @param cbf the CanBuildFrom instance // * @param <A> the type of elements // * @param <C1> optional intermediate representation, see CanBuildFrom javadoc // * @param <C2> the type of the result iterable, see CanBuildFrom javadoc // * @return A DB[C2[A]] // */ // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // } // // /** // * Shorthand of sequence() that returns an fj.data.List // */ // public static <A> DB<fj.data.List<A>> sequence(Iterable<DB<A>> xs) // { // return sequence(xs, fjListCanBuildFrom()); // } // // }
import com.novarto.sanedbc.core.ops.DbOps; import fj.control.db.DB; import fj.function.Try0; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException;
package com.novarto.sanedbc.core.interpreter; /** * A set of utilities to aid in implementing {@link DB} interpreters. */ public final class InterpreterUtils { private InterpreterUtils() { throw new UnsupportedOperationException(); }
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public final class DbOps // { // // private DbOps() // { // throw new UnsupportedOperationException(); // } // // /** // * Given an existing {@link DB<Iterable<A>>}, converts it to an operation that either returns one result, none at all, // * or throws if there is more than one result in the result set. // * // * This is useful if you are issuing a query by a single primary key. Such a query is never expected to return > 1 results // * (in which case the returned DB will throw upon interpretation), but can return no results (which is expressed in the // * return type) // */ // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // } // // // // public static <A> DB<Integer> toChunks(Iterable<A> xs, F<Iterable<A>, DB<Integer>> getOp, int chunkSize) // { // // return new DB<Integer>() // { // @Override public Integer run(Connection c) throws SQLException // { // Integer result = 0; // // List<List<A>> chunks = chunks(xs, chunkSize); // // for (List<A> chunk : chunks) // { // result += getOp.f(chunk).run(c); // } // // return result; // } // }; // // } // // private static <A> List<List<A>> chunks(Iterable<A> xs, int chunkSize) // { // // if (chunkSize < 1) // { // throw new IllegalArgumentException("chunkSize must be >=1"); // } // // List<List<A>> result = new ArrayList<>(); // List<A> currentList = new ArrayList<>(); // result.add(currentList); // int count = 0; // // for (A x : xs) // { // // if (count >= chunkSize) // { // currentList = new ArrayList<>(); // result.add(currentList); // count = 0; // } // // currentList.add(x); // count++; // // } // // List<A> last = result.get(result.size() - 1); // if (last.size() == 0) // { // result.remove(result.size() - 1); // } // // return result; // } // // /** // * Given an iterable of DB's, convert it to a single DB of iterable. E.g. List[DB[A]] => DB[List[A]]. // * Utilizes a CanBuildFrom instance to construct the result iterable // * @param xs the iterable of DB's to convert // * @param cbf the CanBuildFrom instance // * @param <A> the type of elements // * @param <C1> optional intermediate representation, see CanBuildFrom javadoc // * @param <C2> the type of the result iterable, see CanBuildFrom javadoc // * @return A DB[C2[A]] // */ // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // } // // /** // * Shorthand of sequence() that returns an fj.data.List // */ // public static <A> DB<fj.data.List<A>> sequence(Iterable<DB<A>> xs) // { // return sequence(xs, fjListCanBuildFrom()); // } // // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java import com.novarto.sanedbc.core.ops.DbOps; import fj.control.db.DB; import fj.function.Try0; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; package com.novarto.sanedbc.core.interpreter; /** * A set of utilities to aid in implementing {@link DB} interpreters. */ public final class InterpreterUtils { private InterpreterUtils() { throw new UnsupportedOperationException(); }
private static final Logger LOGGER = LoggerFactory.getLogger(DbOps.class);
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/FlywayMigrationExample.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java // public class AggregateOp extends DB<Long> // { // // private final SelectOp.List<Long> selectOp; // // public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); // } // // public AggregateOp(String sql) // { // this(sql, NO_BINDER); // } // // @Override public Long run(Connection c) throws SQLException // { // return selectOp.map(xs -> // { // // Iterator<Long> resultIterator = xs.iterator(); // if (!resultIterator.hasNext()) // { // throw new IllegalStateException("result is empty"); // // } // Long result = resultIterator.next(); // // if (resultIterator.hasNext()) // { // throw new IllegalStateException("result has more than one row"); // } // return result; // }).run(c); // } // // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.AggregateOp; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.examples; /** * Database migrations are a great way to control the state of an application in the database. This is an example of usage of * {@link Flyway} along with sane-dbc. * <p> * This example uses two migrations: * <ul> * <li>Static sql file V1_1_DBInit.sql which is placed in resources dir * <li>JDBC Java Migration {@link com.novarto.sanedbc.examples.flyway.V1_2__AlterFoo} * </ul> * * @see <a href="https://flywaydb.org/">https://flywaydb.org/</a> */ public class FlywayMigrationExample { private static final Flyway FLYWAY = new Flyway(); private static final String FLYWAY_JDBC_URL = "jdbc:hsqldb:mem:flyway"; @BeforeClass public static void setup() { // set schema name FLYWAY.setSchemas("FLYWAY"); // set datasource FLYWAY.setDataSource(FLYWAY_JDBC_URL, "sa", ""); // set location folders which contain migrations that needs to be applied by flyway final String packageName = FlywayMigrationExample.class.getPackage().getName(); final String packageFolder = packageName.replace(".", "/"); final String migrationFolder = packageFolder + "/flyway"; final List<String> migrationFolders = new ArrayList<>(); migrationFolders.add(migrationFolder); migrationFolders.add("flyway"); FLYWAY.setLocations(migrationFolders.toArray(new String[migrationFolders.size()])); // run migrations FLYWAY.migrate(); } @Test public void checkMigrationsAreApplied() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java // public class AggregateOp extends DB<Long> // { // // private final SelectOp.List<Long> selectOp; // // public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); // } // // public AggregateOp(String sql) // { // this(sql, NO_BINDER); // } // // @Override public Long run(Connection c) throws SQLException // { // return selectOp.map(xs -> // { // // Iterator<Long> resultIterator = xs.iterator(); // if (!resultIterator.hasNext()) // { // throw new IllegalStateException("result is empty"); // // } // Long result = resultIterator.next(); // // if (resultIterator.hasNext()) // { // throw new IllegalStateException("result has more than one row"); // } // return result; // }).run(c); // } // // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/FlywayMigrationExample.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.AggregateOp; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.examples; /** * Database migrations are a great way to control the state of an application in the database. This is an example of usage of * {@link Flyway} along with sane-dbc. * <p> * This example uses two migrations: * <ul> * <li>Static sql file V1_1_DBInit.sql which is placed in resources dir * <li>JDBC Java Migration {@link com.novarto.sanedbc.examples.flyway.V1_2__AlterFoo} * </ul> * * @see <a href="https://flywaydb.org/">https://flywaydb.org/</a> */ public class FlywayMigrationExample { private static final Flyway FLYWAY = new Flyway(); private static final String FLYWAY_JDBC_URL = "jdbc:hsqldb:mem:flyway"; @BeforeClass public static void setup() { // set schema name FLYWAY.setSchemas("FLYWAY"); // set datasource FLYWAY.setDataSource(FLYWAY_JDBC_URL, "sa", ""); // set location folders which contain migrations that needs to be applied by flyway final String packageName = FlywayMigrationExample.class.getPackage().getName(); final String packageFolder = packageName.replace(".", "/"); final String migrationFolder = packageFolder + "/flyway"; final List<String> migrationFolders = new ArrayList<>(); migrationFolders.add(migrationFolder); migrationFolders.add("flyway"); FLYWAY.setLocations(migrationFolders.toArray(new String[migrationFolders.size()])); // run migrations FLYWAY.migrate(); } @Test public void checkMigrationsAreApplied() {
SyncDbInterpreter dbi = new SyncDbInterpreter(
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/FlywayMigrationExample.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java // public class AggregateOp extends DB<Long> // { // // private final SelectOp.List<Long> selectOp; // // public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); // } // // public AggregateOp(String sql) // { // this(sql, NO_BINDER); // } // // @Override public Long run(Connection c) throws SQLException // { // return selectOp.map(xs -> // { // // Iterator<Long> resultIterator = xs.iterator(); // if (!resultIterator.hasNext()) // { // throw new IllegalStateException("result is empty"); // // } // Long result = resultIterator.next(); // // if (resultIterator.hasNext()) // { // throw new IllegalStateException("result has more than one row"); // } // return result; // }).run(c); // } // // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.AggregateOp; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.examples; /** * Database migrations are a great way to control the state of an application in the database. This is an example of usage of * {@link Flyway} along with sane-dbc. * <p> * This example uses two migrations: * <ul> * <li>Static sql file V1_1_DBInit.sql which is placed in resources dir * <li>JDBC Java Migration {@link com.novarto.sanedbc.examples.flyway.V1_2__AlterFoo} * </ul> * * @see <a href="https://flywaydb.org/">https://flywaydb.org/</a> */ public class FlywayMigrationExample { private static final Flyway FLYWAY = new Flyway(); private static final String FLYWAY_JDBC_URL = "jdbc:hsqldb:mem:flyway"; @BeforeClass public static void setup() { // set schema name FLYWAY.setSchemas("FLYWAY"); // set datasource FLYWAY.setDataSource(FLYWAY_JDBC_URL, "sa", ""); // set location folders which contain migrations that needs to be applied by flyway final String packageName = FlywayMigrationExample.class.getPackage().getName(); final String packageFolder = packageName.replace(".", "/"); final String migrationFolder = packageFolder + "/flyway"; final List<String> migrationFolders = new ArrayList<>(); migrationFolders.add(migrationFolder); migrationFolders.add("flyway"); FLYWAY.setLocations(migrationFolders.toArray(new String[migrationFolders.size()])); // run migrations FLYWAY.migrate(); } @Test public void checkMigrationsAreApplied() { SyncDbInterpreter dbi = new SyncDbInterpreter( // provide a piece of code which knows how to spawn connections // in this case we are just using the DriverManager () -> DriverManager.getConnection(FLYWAY_JDBC_URL, "sa", "") ); // check that after flyway migrations are applied the count of FOO is 3
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java // public class AggregateOp extends DB<Long> // { // // private final SelectOp.List<Long> selectOp; // // public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); // } // // public AggregateOp(String sql) // { // this(sql, NO_BINDER); // } // // @Override public Long run(Connection c) throws SQLException // { // return selectOp.map(xs -> // { // // Iterator<Long> resultIterator = xs.iterator(); // if (!resultIterator.hasNext()) // { // throw new IllegalStateException("result is empty"); // // } // Long result = resultIterator.next(); // // if (resultIterator.hasNext()) // { // throw new IllegalStateException("result has more than one row"); // } // return result; // }).run(c); // } // // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/FlywayMigrationExample.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.AggregateOp; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.examples; /** * Database migrations are a great way to control the state of an application in the database. This is an example of usage of * {@link Flyway} along with sane-dbc. * <p> * This example uses two migrations: * <ul> * <li>Static sql file V1_1_DBInit.sql which is placed in resources dir * <li>JDBC Java Migration {@link com.novarto.sanedbc.examples.flyway.V1_2__AlterFoo} * </ul> * * @see <a href="https://flywaydb.org/">https://flywaydb.org/</a> */ public class FlywayMigrationExample { private static final Flyway FLYWAY = new Flyway(); private static final String FLYWAY_JDBC_URL = "jdbc:hsqldb:mem:flyway"; @BeforeClass public static void setup() { // set schema name FLYWAY.setSchemas("FLYWAY"); // set datasource FLYWAY.setDataSource(FLYWAY_JDBC_URL, "sa", ""); // set location folders which contain migrations that needs to be applied by flyway final String packageName = FlywayMigrationExample.class.getPackage().getName(); final String packageFolder = packageName.replace(".", "/"); final String migrationFolder = packageFolder + "/flyway"; final List<String> migrationFolders = new ArrayList<>(); migrationFolders.add(migrationFolder); migrationFolders.add("flyway"); FLYWAY.setLocations(migrationFolders.toArray(new String[migrationFolders.size()])); // run migrations FLYWAY.migrate(); } @Test public void checkMigrationsAreApplied() { SyncDbInterpreter dbi = new SyncDbInterpreter( // provide a piece of code which knows how to spawn connections // in this case we are just using the DriverManager () -> DriverManager.getConnection(FLYWAY_JDBC_URL, "sa", "") ); // check that after flyway migrations are applied the count of FOO is 3
final Long count = dbi.submit(new AggregateOp("SELECT COUNT(*) FROM FLYWAY.FOO"));
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import fj.control.db.DB; import fj.function.TryEffect1; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER;
package com.novarto.sanedbc.core.ops; public class AggregateOp extends DB<Long> { private final SelectOp.List<Long> selectOp; public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) { this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); } public AggregateOp(String sql) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/AggregateOp.java import fj.control.db.DB; import fj.function.TryEffect1; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; package com.novarto.sanedbc.core.ops; public class AggregateOp extends DB<Long> { private final SelectOp.List<Long> selectOp; public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) { this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); } public AggregateOp(String sql) {
this(sql, NO_BINDER);
novarto-oss/sane-dbc
sane-dbc-guava/src/main/java/com/novarto/sanedbc/guava/GuavaDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.guava; /** * A {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in a Guava ListeningExecutorService. * The ListenableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class GuavaDbInterpreter { private final Try0<Connection, SQLException> ds; private final ListeningExecutorService ex; public GuavaDbInterpreter(Try0<Connection, SQLException> ds, ListeningExecutorService ex) { this.ds = ds; this.ex = ex; } public GuavaDbInterpreter(DataSource ds, ListeningExecutorService ex) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-guava/src/main/java/com/novarto/sanedbc/guava/GuavaDbInterpreter.java import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.guava; /** * A {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in a Guava ListeningExecutorService. * The ListenableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class GuavaDbInterpreter { private final Try0<Connection, SQLException> ds; private final ListeningExecutorService ex; public GuavaDbInterpreter(Try0<Connection, SQLException> ds, ListeningExecutorService ex) { this.ds = ds; this.ex = ex; } public GuavaDbInterpreter(DataSource ds, ListeningExecutorService ex) {
this(lift(ds), ex);
novarto-oss/sane-dbc
sane-dbc-guava/src/main/java/com/novarto/sanedbc/guava/GuavaDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.guava; /** * A {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in a Guava ListeningExecutorService. * The ListenableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class GuavaDbInterpreter { private final Try0<Connection, SQLException> ds; private final ListeningExecutorService ex; public GuavaDbInterpreter(Try0<Connection, SQLException> ds, ListeningExecutorService ex) { this.ds = ds; this.ex = ex; } public GuavaDbInterpreter(DataSource ds, ListeningExecutorService ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> ListenableFuture<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> ListenableFuture<A> transact(DB<A> op) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-guava/src/main/java/com/novarto/sanedbc/guava/GuavaDbInterpreter.java import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.guava; /** * A {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in a Guava ListeningExecutorService. * The ListenableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class GuavaDbInterpreter { private final Try0<Connection, SQLException> ds; private final ListeningExecutorService ex; public GuavaDbInterpreter(Try0<Connection, SQLException> ds, ListeningExecutorService ex) { this.ds = ds; this.ex = ex; } public GuavaDbInterpreter(DataSource ds, ListeningExecutorService ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> ListenableFuture<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> ListenableFuture<A> transact(DB<A> op) {
return withConnection(transactional(op), false);
novarto-oss/sane-dbc
sane-dbc-guava/src/test/java/com/novarto/sanedbc/guava/SanityTest.java
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // }
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGet; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGetFailure; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.guava; public class SanityTest { private static GuavaDbInterpreter dbAsync; private static HikariDataSource ds; private static ListeningExecutorService ex; @BeforeClass public static void setupHikari() {
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // Path: sane-dbc-guava/src/test/java/com/novarto/sanedbc/guava/SanityTest.java import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGet; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGetFailure; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.guava; public class SanityTest { private static GuavaDbInterpreter dbAsync; private static HikariDataSource ds; private static ListeningExecutorService ex; @BeforeClass public static void setupHikari() {
ds = Hikari.createHikari("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "", new Properties());
novarto-oss/sane-dbc
sane-dbc-guava/src/test/java/com/novarto/sanedbc/guava/SanityTest.java
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // }
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGet; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGetFailure; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.guava; public class SanityTest { private static GuavaDbInterpreter dbAsync; private static HikariDataSource ds; private static ListeningExecutorService ex; @BeforeClass public static void setupHikari() { ds = Hikari.createHikari("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "", new Properties()); ex = MoreExecutors.listeningDecorator(Hikari.createExecutorFor(ds, false)); dbAsync = new GuavaDbInterpreter(ds, ex); } @Test public void sanity() { ListenableFuture<Integer> success = dbAsync.submit(DB.unit(42)); SQLException ex = new SQLException("failed i have"); ListenableFuture<Integer> fail = dbAsync.submit(DB.db((Try1<Connection, Integer, SQLException>) c -> { assertThat(c, is(notNullValue())); throw ex; })); assertThat(awaitAndGet(success), is(42)); assertThat(awaitAndGetFailure(fail), is(ex)); } @AfterClass public static void shutdownHikari() {
// Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public class Hikari // { // private static final Logger LOGGER = LoggerFactory.getLogger(Hikari.class); // // public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) // { // HikariConfig config = new HikariConfig(); // // config.setJdbcUrl(url); // config.setUsername(user); // config.setPassword(pass); // // config.setDataSourceProperties(dsProps); // // LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); // // return new HikariDataSource(config); // } // // public static ExecutorService createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit) // { // return createExecutorFor(ds, shutdownOnJvmExit, Executors::newCachedThreadPool); // // } // // public static <A extends ExecutorService> A createExecutorFor(HikariDataSource ds, boolean shutdownOnJvmExit, // F0<A> ctor // ) // { // A executor = ctor.f(); // // if (shutdownOnJvmExit) // { // String serviceName = "Shutdown hook for hikari@" + ds.getJdbcUrl(); // final Thread datasourceShutdownHook = new Thread(() -> gracefulShutdown(executor, ds)); // datasourceShutdownHook.setName(serviceName); // Runtime.getRuntime().addShutdownHook(datasourceShutdownHook); // // } // // return executor; // // } // // // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // // } // // Path: sane-dbc-hikari/src/main/java/com/novarto/sanedbc/hikari/Hikari.java // public static void gracefulShutdown(ExecutorService ex, HikariDataSource ds) // { // ds.close(); // ConcurrentUtil.shutdownAndAwaitTermination(ex, 5, TimeUnit.SECONDS); // } // Path: sane-dbc-guava/src/test/java/com/novarto/sanedbc/guava/SanityTest.java import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.novarto.sanedbc.hikari.Hikari; import com.zaxxer.hikari.HikariDataSource; import fj.control.db.DB; import fj.function.Try1; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGet; import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGetFailure; import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.guava; public class SanityTest { private static GuavaDbInterpreter dbAsync; private static HikariDataSource ds; private static ListeningExecutorService ex; @BeforeClass public static void setupHikari() { ds = Hikari.createHikari("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "", new Properties()); ex = MoreExecutors.listeningDecorator(Hikari.createExecutorFor(ds, false)); dbAsync = new GuavaDbInterpreter(ds, ex); } @Test public void sanity() { ListenableFuture<Integer> success = dbAsync.submit(DB.unit(42)); SQLException ex = new SQLException("failed i have"); ListenableFuture<Integer> fail = dbAsync.submit(DB.db((Try1<Connection, Integer, SQLException>) c -> { assertThat(c, is(notNullValue())); throw ex; })); assertThat(awaitAndGet(success), is(42)); assertThat(awaitAndGetFailure(fail), is(ex)); } @AfterClass public static void shutdownHikari() {
gracefulShutdown(ex, ds);
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/SqlStringUtils.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/SqlStringUtils.java // public enum StatementKind // { // SELECT, UPDATE, DELETE, INSERT, UNKNOWN // }
import fj.function.Effect2; import static com.novarto.sanedbc.core.SqlStringUtils.StatementKind.*; import static java.text.MessageFormat.format;
/** * Shorthand for whereExpressionWithPlaceholders(colNames, AND) */ public static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames) { return whereExpressionWithPlaceholders(colNames, LogicalOperator.AND); } private static StringBuilder expressionWithPlaceholders(Iterable<String> colNames, String separator) { StringBuilder result = new StringBuilder(); for (String colName : colNames) { result.append(colName).append("=?").append(separator); } return result.delete(result.length() - separator.length(), result.length()); } /** * Tries to detect the type of an sql statement as one of the enums in StatementKind. * This method does no lexing or parsing, and almost no normalization, trying to strike a balance * between efficiency and utility. It is not intended to be used in application code. Its result should * only be interpreted as a hint. * @param sql * @return a value hinting the statement kind */
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/SqlStringUtils.java // public enum StatementKind // { // SELECT, UPDATE, DELETE, INSERT, UNKNOWN // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/SqlStringUtils.java import fj.function.Effect2; import static com.novarto.sanedbc.core.SqlStringUtils.StatementKind.*; import static java.text.MessageFormat.format; /** * Shorthand for whereExpressionWithPlaceholders(colNames, AND) */ public static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames) { return whereExpressionWithPlaceholders(colNames, LogicalOperator.AND); } private static StringBuilder expressionWithPlaceholders(Iterable<String> colNames, String separator) { StringBuilder result = new StringBuilder(); for (String colName : colNames) { result.append(colName).append("=?").append(separator); } return result.delete(result.length() - separator.length(), result.length()); } /** * Tries to detect the type of an sql statement as one of the enums in StatementKind. * This method does no lexing or parsing, and almost no normalization, trying to strike a balance * between efficiency and utility. It is not intended to be used in application code. Its result should * only be interpreted as a hint. * @param sql * @return a value hinting the statement kind */
public static StatementKind getStatementKind(String sql)
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import fj.P1; import fj.Try; import fj.control.db.DB; import fj.data.Validation; import fj.function.Try0; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.core.interpreter; public class ValidationDbInterpreter { private final Try0<Connection, SQLException> ds; public ValidationDbInterpreter(Try0<Connection, SQLException> ds) { this.ds = ds; } public <A> P1<Validation<Exception, A>> submit(DB<A> db) { return Try.<A, Exception>f(() -> { try (Connection c = ds.f()) { return db.run(c); } }); } public <A> P1<Validation<Exception, A>> transact(DB<A> db) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/ValidationDbInterpreter.java import fj.P1; import fj.Try; import fj.control.db.DB; import fj.data.Validation; import fj.function.Try0; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.core.interpreter; public class ValidationDbInterpreter { private final Try0<Connection, SQLException> ds; public ValidationDbInterpreter(Try0<Connection, SQLException> ds) { this.ds = ds; } public <A> P1<Validation<Exception, A>> submit(DB<A> db) { return Try.<A, Exception>f(() -> { try (Connection c = ds.f()) { return db.run(c); } }); } public <A> P1<Validation<Exception, A>> transact(DB<A> db) {
return submit(transactional(db));
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import fj.control.db.DB; import fj.function.Try0; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.core.interpreter; /** * An interpreter for DB operations which blocks the caller thread. In addition it rethrows any SQL Exceptions as runtime ones. * Mostly useful for testing purposes. * */ public class SyncDbInterpreter { private final Try0<Connection, SQLException> ds; /** * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, * Driver Manager, etc. * @param ds - the data source, which can spawn connections */ public SyncDbInterpreter(Try0<Connection, SQLException> ds) { this.ds = ds; } /** * Attempt to run this operation and return its result * @param doOp the operation to run * @param <A> the result type of the operation * @return the successful result * @throws RuntimeException if an {@link SQLException} is encountered */ public <A> A submit(DB<A> doOp) { try (Connection c = ds.f()) { return doOp.run(c); } catch (SQLException e) { throw new RuntimeException(e); } } /** * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is * encountered, the operation is rolled back. * @param doOp the operation to run * @param <A> the result type of the operation * @return the successful result * @throws RuntimeException if an {@link SQLException} is encountered */ public <A> A transact(DB<A> doOp) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java import fj.control.db.DB; import fj.function.Try0; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.core.interpreter; /** * An interpreter for DB operations which blocks the caller thread. In addition it rethrows any SQL Exceptions as runtime ones. * Mostly useful for testing purposes. * */ public class SyncDbInterpreter { private final Try0<Connection, SQLException> ds; /** * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, * Driver Manager, etc. * @param ds - the data source, which can spawn connections */ public SyncDbInterpreter(Try0<Connection, SQLException> ds) { this.ds = ds; } /** * Attempt to run this operation and return its result * @param doOp the operation to run * @param <A> the result type of the operation * @return the successful result * @throws RuntimeException if an {@link SQLException} is encountered */ public <A> A submit(DB<A> doOp) { try (Connection c = ds.f()) { return doOp.run(c); } catch (SQLException e) { throw new RuntimeException(e); } } /** * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is * encountered, the operation is rolled back. * @param doOp the operation to run * @param <A> the result type of the operation * @return the successful result * @throws RuntimeException if an {@link SQLException} is encountered */ public <A> A transact(DB<A> doOp) {
return submit(transactional(doOp));
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/SequenceExample.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.control.db.DB; import fj.data.List; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.sequence; import static fj.data.List.arrayList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.examples; public class SequenceExample { @Test public void testIt() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/SequenceExample.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.control.db.DB; import fj.data.List; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.sequence; import static fj.data.List.arrayList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.examples; public class SequenceExample { @Test public void testIt() {
SyncDbInterpreter dbi = new SyncDbInterpreter(
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/SequenceExample.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.control.db.DB; import fj.data.List; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.sequence; import static fj.data.List.arrayList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.examples; public class SequenceExample { @Test public void testIt() { SyncDbInterpreter dbi = new SyncDbInterpreter( () -> DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", "") ); //given an iterable of DB's List<DB<String>> dbList = arrayList( DB.unit("foo"), DB.unit("bar"), DB.unit("baz") ); //we can treat it as a DB<List>
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A, C1 extends Iterable<A>, C2 extends Iterable<A>> DB<C2> sequence(Iterable<DB<A>> xs, // CanBuildFrom<A, C1, C2> cbf) // { // DB<C1> acc = DB.unit(cbf.createBuffer()); // for (DB<A> db : xs) // { // DB<C1> fAcc = acc; // acc = db.bind(x -> fAcc.map(ys -> cbf.add(x, ys))); // } // // return acc.map(cbf::build); // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/SequenceExample.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import fj.control.db.DB; import fj.data.List; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.sequence; import static fj.data.List.arrayList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.examples; public class SequenceExample { @Test public void testIt() { SyncDbInterpreter dbi = new SyncDbInterpreter( () -> DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", "") ); //given an iterable of DB's List<DB<String>> dbList = arrayList( DB.unit("foo"), DB.unit("bar"), DB.unit("baz") ); //we can treat it as a DB<List>
DB<List<String>> db = sequence(dbList);
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import com.novarto.lang.SneakyThrow; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.core.interpreter; /** * A standard {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in an ExecutorService. The result is lifted to a CompletableFuture. * The CompletableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted DB operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class AsyncDbInterpreter { private final Try0<Connection, SQLException> ds; private final ExecutorService executor; public AsyncDbInterpreter(Try0<Connection, SQLException> ds, ExecutorService ex) { this.ds = ds; this.executor = ex; } public AsyncDbInterpreter(DataSource ds, ExecutorService ex) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreter.java import com.novarto.lang.SneakyThrow; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.core.interpreter; /** * A standard {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in an ExecutorService. The result is lifted to a CompletableFuture. * The CompletableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted DB operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class AsyncDbInterpreter { private final Try0<Connection, SQLException> ds; private final ExecutorService executor; public AsyncDbInterpreter(Try0<Connection, SQLException> ds, ExecutorService ex) { this.ds = ds; this.executor = ex; } public AsyncDbInterpreter(DataSource ds, ExecutorService ex) {
this(lift(ds), ex);
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import com.novarto.lang.SneakyThrow; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.core.interpreter; /** * A standard {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in an ExecutorService. The result is lifted to a CompletableFuture. * The CompletableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted DB operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class AsyncDbInterpreter { private final Try0<Connection, SQLException> ds; private final ExecutorService executor; public AsyncDbInterpreter(Try0<Connection, SQLException> ds, ExecutorService ex) { this.ds = ds; this.executor = ex; } public AsyncDbInterpreter(DataSource ds, ExecutorService ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> CompletableFuture<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> CompletableFuture<A> transact(DB<A> op) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreter.java import com.novarto.lang.SneakyThrow; import fj.control.db.DB; import fj.function.Try0; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.core.interpreter; /** * A standard {@link DB} interpreter that utilizes a data source to spawn connections, * and submits {@link DB} instances for execution in an ExecutorService. The result is lifted to a CompletableFuture. * The CompletableFuture returned will fail iff the underlying DB throws. * * Spawning of a connection happens inside an executor service thread, the submitted DB operation is executed in the same thread, * and then the connection is closed. Therefore, a connection obtained from the pool is accessed by only a single thread * before being returned to the pool. * */ public class AsyncDbInterpreter { private final Try0<Connection, SQLException> ds; private final ExecutorService executor; public AsyncDbInterpreter(Try0<Connection, SQLException> ds, ExecutorService ex) { this.ds = ds; this.executor = ex; } public AsyncDbInterpreter(DataSource ds, ExecutorService ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> CompletableFuture<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> CompletableFuture<A> transact(DB<A> op) {
return withConnection(transactional(op), false);
novarto-oss/sane-dbc
sane-dbc-netty/src/main/java/com/novarto/sanedbc/netty/FutureInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import fj.control.db.DB; import fj.function.Try0; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.netty; public class FutureInterpreter { private final Try0<Connection, SQLException> ds; private final EventExecutorGroup ex; public FutureInterpreter(Try0<Connection, SQLException> ds, EventExecutorGroup ex) { this.ds = ds; this.ex = ex; } public FutureInterpreter(DataSource ds, EventExecutorGroup ex) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-netty/src/main/java/com/novarto/sanedbc/netty/FutureInterpreter.java import fj.control.db.DB; import fj.function.Try0; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.netty; public class FutureInterpreter { private final Try0<Connection, SQLException> ds; private final EventExecutorGroup ex; public FutureInterpreter(Try0<Connection, SQLException> ds, EventExecutorGroup ex) { this.ds = ds; this.ex = ex; } public FutureInterpreter(DataSource ds, EventExecutorGroup ex) {
this(lift(ds), ex);
novarto-oss/sane-dbc
sane-dbc-netty/src/main/java/com/novarto/sanedbc/netty/FutureInterpreter.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // }
import fj.control.db.DB; import fj.function.Try0; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
package com.novarto.sanedbc.netty; public class FutureInterpreter { private final Try0<Connection, SQLException> ds; private final EventExecutorGroup ex; public FutureInterpreter(Try0<Connection, SQLException> ds, EventExecutorGroup ex) { this.ds = ds; this.ex = ex; } public FutureInterpreter(DataSource ds, EventExecutorGroup ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> Future<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> Future<A> transact(DB<A> op) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static <A> DB<A> transactional(DB<A> op) // { // // return new DB<A>() // { // @Override public A run(Connection c) throws SQLException // { // final boolean wasAutocommit = c.getAutoCommit(); // Throwable th = null; // if (wasAutocommit) // { // c.setAutoCommit(false); // } // // try // { // A result = op.run(c); // c.commit(); // return result; // } // catch (Throwable e) // { // th = e; // c.rollback(); // throw e; // // } // finally // { // try // { // if (wasAutocommit) // { // c.setAutoCommit(true); // } // } // catch (SQLException e) // { // if (th != null) // { // th.addSuppressed(e); // } // else // { // throw e; // } // } // } // // } // }; // } // Path: sane-dbc-netty/src/main/java/com/novarto/sanedbc/netty/FutureInterpreter.java import fj.control.db.DB; import fj.function.Try0; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional; package com.novarto.sanedbc.netty; public class FutureInterpreter { private final Try0<Connection, SQLException> ds; private final EventExecutorGroup ex; public FutureInterpreter(Try0<Connection, SQLException> ds, EventExecutorGroup ex) { this.ds = ds; this.ex = ex; } public FutureInterpreter(DataSource ds, EventExecutorGroup ex) { this(lift(ds), ex); } /** * Submits this operation for execution in the executor service. The operation is executed with connection autoCommit = true, * i.e. non-transactionally. */ public <A> Future<A> submit(DB<A> op) { return withConnection(op, true); } /** * Submits this operation for execution in the executor service. The operation is executed as a transaction. */ public <A> Future<A> transact(DB<A> op) {
return withConnection(transactional(op), false);
novarto-oss/sane-dbc
sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/BatchInsertGenKeysOp.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static <A> Try1<PreparedStatement, Option<Integer>, SQLException> batchBinder( // F<A, TryEffect1<PreparedStatement, SQLException>> binder, Iterable<A> as) // { // return ps -> { // for (A a : as) // { // binder.f(a).f(ps); // ps.addBatch(); // } // return sumBatchResult(ps.executeBatch()); // // }; // }
import com.novarto.lang.CanBuildFrom; import com.novarto.lang.Collections; import fj.F; import fj.control.db.DB; import fj.data.Option; import fj.function.Try1; import fj.function.TryEffect1; import java.sql.*; import static com.novarto.sanedbc.core.ops.Binders.batchBinder;
package com.novarto.sanedbc.core.ops; /** * Batch insert operation which returns the auto-generated keys created for the inserted entries. Please consider that the used * JDBC driver may not support the retrieval of auto-generated key and this operation may fail with {@link * SQLFeatureNotSupportedException} * * @param <A> Type of single entry to be inserted * @param <B> Type of the result which must extend {@link Number} * @param <C1> The type of the optional (mutable) buffer which is intermediately used while constructing the result. * @param <C2> Type of the result * @see Statement#getGeneratedKeys() */ public abstract class BatchInsertGenKeysOp<A, B extends Number, C1 extends Iterable<B>, C2 extends Iterable<B>> extends DB<C2> { private final String sql; private final Try1<PreparedStatement, Option<Integer>, SQLException> binder; private final Try1<ResultSet, B, SQLException> getKey; private final CanBuildFrom<B, C1, C2> cbf; private final Iterable<A> as; public BatchInsertGenKeysOp(String sql, F<A, TryEffect1<PreparedStatement, SQLException>> binder, Iterable<A> as, Try1<ResultSet, B, SQLException> getKey, CanBuildFrom<B, C1, C2> cbf) { this.sql = sql;
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static <A> Try1<PreparedStatement, Option<Integer>, SQLException> batchBinder( // F<A, TryEffect1<PreparedStatement, SQLException>> binder, Iterable<A> as) // { // return ps -> { // for (A a : as) // { // binder.f(a).f(ps); // ps.addBatch(); // } // return sumBatchResult(ps.executeBatch()); // // }; // } // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/BatchInsertGenKeysOp.java import com.novarto.lang.CanBuildFrom; import com.novarto.lang.Collections; import fj.F; import fj.control.db.DB; import fj.data.Option; import fj.function.Try1; import fj.function.TryEffect1; import java.sql.*; import static com.novarto.sanedbc.core.ops.Binders.batchBinder; package com.novarto.sanedbc.core.ops; /** * Batch insert operation which returns the auto-generated keys created for the inserted entries. Please consider that the used * JDBC driver may not support the retrieval of auto-generated key and this operation may fail with {@link * SQLFeatureNotSupportedException} * * @param <A> Type of single entry to be inserted * @param <B> Type of the result which must extend {@link Number} * @param <C1> The type of the optional (mutable) buffer which is intermediately used while constructing the result. * @param <C2> Type of the result * @see Statement#getGeneratedKeys() */ public abstract class BatchInsertGenKeysOp<A, B extends Number, C1 extends Iterable<B>, C2 extends Iterable<B>> extends DB<C2> { private final String sql; private final Try1<PreparedStatement, Option<Integer>, SQLException> binder; private final Try1<ResultSet, B, SQLException> getKey; private final CanBuildFrom<B, C1, C2> cbf; private final Iterable<A> as; public BatchInsertGenKeysOp(String sql, F<A, TryEffect1<PreparedStatement, SQLException>> binder, Iterable<A> as, Try1<ResultSet, B, SQLException> getKey, CanBuildFrom<B, C1, C2> cbf) { this.sql = sql;
this.binder = batchBinder(binder, as);
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/BasicUsage.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.*; import fj.Unit; import fj.control.db.DB; import fj.data.List; import fj.data.Option; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.unique; import static fj.data.List.nil; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
A mapper is a function which maps a single row from the resultset to a single object A generic SelectOp also needs to be told what collection to use in the result The SelectOp.FjList specialization uses fj.data.List, which is an immutable singly-linked list. (Also known as Cons list) There is also a specialization for java Lists; or you can supply your own collection builder */ return new SelectOp.FjList<>( "SELECT ID, DESCRIPTION FROM STUFF WHERE DESCRIPTION=?", ps -> ps.setString(1, description), //build a Stuff from a resultset row rs -> new Stuff(rs.getInt(1), rs.getString(2)) ); } /* Select an entry by id The return type is fj.data.Option, since it may be that no entry with this id exists fj.data.Option is equivalent to Java Optional */ public static DB<Option<Stuff>> selectByKey(int id) { //given a regular operation which returns an iterable: DB<List<Stuff>> temp = new SelectOp.FjList<>( "SELECT ID, DESCRIPTION FROM STUFF WHERE ID=?", ps -> ps.setInt(1, id), rs -> new Stuff(rs.getInt(1), rs.getString(2))); // using the unique() function, // we can convert it to an operation which expects at most one result, and returns that optional result:
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/BasicUsage.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.*; import fj.Unit; import fj.control.db.DB; import fj.data.List; import fj.data.Option; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.unique; import static fj.data.List.nil; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; A mapper is a function which maps a single row from the resultset to a single object A generic SelectOp also needs to be told what collection to use in the result The SelectOp.FjList specialization uses fj.data.List, which is an immutable singly-linked list. (Also known as Cons list) There is also a specialization for java Lists; or you can supply your own collection builder */ return new SelectOp.FjList<>( "SELECT ID, DESCRIPTION FROM STUFF WHERE DESCRIPTION=?", ps -> ps.setString(1, description), //build a Stuff from a resultset row rs -> new Stuff(rs.getInt(1), rs.getString(2)) ); } /* Select an entry by id The return type is fj.data.Option, since it may be that no entry with this id exists fj.data.Option is equivalent to Java Optional */ public static DB<Option<Stuff>> selectByKey(int id) { //given a regular operation which returns an iterable: DB<List<Stuff>> temp = new SelectOp.FjList<>( "SELECT ID, DESCRIPTION FROM STUFF WHERE ID=?", ps -> ps.setInt(1, id), rs -> new Stuff(rs.getInt(1), rs.getString(2))); // using the unique() function, // we can convert it to an operation which expects at most one result, and returns that optional result:
return unique(temp);
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/BasicUsage.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // }
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.*; import fj.Unit; import fj.control.db.DB; import fj.data.List; import fj.data.Option; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.unique; import static fj.data.List.nil; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
"INSERT INTO STUFF(DESCRIPTION) VALUES(?)", //given the current element of the iterable, return a binder which sets the parameters for that element // if you extracted the binder from the previous operations in a field named SET_DESCRIPTION, code becomes // description -> SET_DESCRIPTION description -> ps -> ps.setString(1, description), //the iterables to insert descriptions ); } /* Count all entries in the table, where the description is LIKE the passed parameter */ public static DB<Long> count(String like) { String searchQuery = like.trim(); //an aggregate op expects the resultset to have one element, and that element to be cast to long //useful for numeric aggregate operations return new AggregateOp("SELECT COUNT(*) FROM STUFF WHERE LOWER(DESCRIPTION) LIKE LOWER(?)", ps -> ps.setString(1, searchQuery + "%") ); } } @Test public void testIt() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/SyncDbInterpreter.java // public class SyncDbInterpreter // { // private final Try0<Connection, SQLException> ds; // // /** // * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool, // * Driver Manager, etc. // * @param ds - the data source, which can spawn connections // */ // public SyncDbInterpreter(Try0<Connection, SQLException> ds) // { // this.ds = ds; // } // // /** // * Attempt to run this operation and return its result // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A submit(DB<A> doOp) // { // try (Connection c = ds.f()) // { // return doOp.run(c); // } // catch (SQLException e) // { // throw new RuntimeException(e); // } // // } // // /** // * Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is // * encountered, the operation is rolled back. // * @param doOp the operation to run // * @param <A> the result type of the operation // * @return the successful result // * @throws RuntimeException if an {@link SQLException} is encountered // */ // public <A> A transact(DB<A> doOp) // { // // return submit(transactional(doOp)); // // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/DbOps.java // public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op) // { // return op.map(xs -> // { // Iterator<A> it = xs.iterator(); // if (!it.hasNext()) // { // return none(); // } // // A result = it.next(); // // if (it.hasNext()) // { // throw new RuntimeException("unique with more than one element"); // } // return some(result); // }); // } // Path: sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/BasicUsage.java import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.*; import fj.Unit; import fj.control.db.DB; import fj.data.List; import fj.data.Option; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.unique; import static fj.data.List.nil; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; "INSERT INTO STUFF(DESCRIPTION) VALUES(?)", //given the current element of the iterable, return a binder which sets the parameters for that element // if you extracted the binder from the previous operations in a field named SET_DESCRIPTION, code becomes // description -> SET_DESCRIPTION description -> ps -> ps.setString(1, description), //the iterables to insert descriptions ); } /* Count all entries in the table, where the description is LIKE the passed parameter */ public static DB<Long> count(String like) { String searchQuery = like.trim(); //an aggregate op expects the resultset to have one element, and that element to be cast to long //useful for numeric aggregate operations return new AggregateOp("SELECT COUNT(*) FROM STUFF WHERE LOWER(DESCRIPTION) LIKE LOWER(?)", ps -> ps.setString(1, searchQuery + "%") ); } } @Test public void testIt() {
SyncDbInterpreter dbi = new SyncDbInterpreter(
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.core.interpreter; public class AsyncDbInterpreterTest { private static AsyncDbInterpreter dbi; private static SyncDbInterpreter sync; private static ExecutorService executor; private static JDBCPool ds; @BeforeClass public static void setupSuite() { executor = Executors.newCachedThreadPool(); ds = new JDBCPool(); ds.setURL("jdbc:hsqldb:mem:JdbcUtilsTest"); ds.setUser("sa"); ds.setPassword(""); dbi = new AsyncDbInterpreter(ds, executor);
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.core.interpreter; public class AsyncDbInterpreterTest { private static AsyncDbInterpreter dbi; private static SyncDbInterpreter sync; private static ExecutorService executor; private static JDBCPool ds; @BeforeClass public static void setupSuite() { executor = Executors.newCachedThreadPool(); ds = new JDBCPool(); ds.setURL("jdbc:hsqldb:mem:JdbcUtilsTest"); ds.setUser("sa"); ds.setPassword(""); dbi = new AsyncDbInterpreter(ds, executor);
sync = new SyncDbInterpreter(lift(ds));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.core.interpreter; public class AsyncDbInterpreterTest { private static AsyncDbInterpreter dbi; private static SyncDbInterpreter sync; private static ExecutorService executor; private static JDBCPool ds; @BeforeClass public static void setupSuite() { executor = Executors.newCachedThreadPool(); ds = new JDBCPool(); ds.setURL("jdbc:hsqldb:mem:JdbcUtilsTest"); ds.setUser("sa"); ds.setPassword(""); dbi = new AsyncDbInterpreter(ds, executor); sync = new SyncDbInterpreter(lift(ds));
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.novarto.sanedbc.core.interpreter; public class AsyncDbInterpreterTest { private static AsyncDbInterpreter dbi; private static SyncDbInterpreter sync; private static ExecutorService executor; private static JDBCPool ds; @BeforeClass public static void setupSuite() { executor = Executors.newCachedThreadPool(); ds = new JDBCPool(); ds.setURL("jdbc:hsqldb:mem:JdbcUtilsTest"); ds.setUser("sa"); ds.setPassword(""); dbi = new AsyncDbInterpreter(ds, executor); sync = new SyncDbInterpreter(lift(ds));
sync.transact(new EffectOp("CREATE TABLE BAR (BAZ VARCHAR(100))"));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
insert("a").run(c); insert("b").run(c); throw ex; } })), is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; insert("a").run(c); insert("b").run(c); throw ex; } })), is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) {
return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
return new SelectOp.FjList<>("SELECT * FROM BAR", NO_BINDER, rs -> rs.getString(1));
novarto-oss/sane-dbc
sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // };
import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
// Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/EffectOp.java // public class EffectOp extends DB<Unit> // { // // private final UpdateOp op; // // public EffectOp(String sql) // { // this.op = new UpdateOp(sql, NO_BINDER); // } // // @Override public Unit run(Connection c) throws SQLException // { // op.run(c); // return Unit.unit(); // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/SelectOp.java // public class SelectOp<A, C1 extends Iterable<A>, C2 extends Iterable<A>> extends AbstractSelectOp<C2> // { // // private final CanBuildFrom<A, C1, C2> cbf; // private final Try1<ResultSet, A, SQLException> mapper; // // /** // * // * @param sql the query to execute // * @param binder a function to bind the PreparedStatement parameters // * @param mapper a function mapping a single ResultSet row to a single element of the result iterable. The function // * must not advance or modify the ResultSet state, i.e. by calling next() // * @param cbf the CanBuildFrom to construct the result iterable // */ // public SelectOp(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper, CanBuildFrom<A, C1, C2> cbf) // { // // super(sql, binder); // this.mapper = mapper; // this.cbf = cbf; // } // // @Override protected C2 doRun(ResultSet rs) throws SQLException // { // C1 buf = cbf.createBuffer(); // // while (rs.next()) // { // buf = cbf.add(mapper.f(rs), buf); // } // // // return cbf.build(buf); // } // // /** // * A convenience SelectOp specialized for java.util.List // */ // public static final class List<A> extends SelectOp<A, java.util.List<A>, java.util.List<A>> // { // // public List(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.listCanBuildFrom()); // } // // } // // /** // * A convenience SelectOp specialized for fj.data.List, utilizing a fj.data.List.Buffer as an intermediate result // */ // public static final class FjList<A> extends SelectOp<A, fj.data.List.Buffer<A>, fj.data.List<A>> // { // // public FjList(String sql, TryEffect1<PreparedStatement, SQLException> binder, // Try1<ResultSet, A, SQLException> mapper) // { // super(sql, binder, mapper, CanBuildFrom.fjListCanBuildFrom()); // } // // } // // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/UpdateOp.java // public class UpdateOp extends DB<Integer> // { // private final String sql; // private final TryEffect1<PreparedStatement, SQLException> binder; // // public UpdateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) // { // this.sql = sql; // this.binder = binder; // } // // // @Override // public Integer run(Connection c) throws SQLException // { // try (PreparedStatement s = c.prepareStatement(sql)) // { // binder.f(s); // return s.executeUpdate(); // } // } // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/interpreter/InterpreterUtils.java // public static Try0<Connection, SQLException> lift(DataSource ds) // { // return ds::getConnection; // } // // Path: sane-dbc-core/src/main/java/com/novarto/sanedbc/core/ops/Binders.java // public static final TryEffect1<PreparedStatement, SQLException> NO_BINDER = (s) -> { // }; // Path: sane-dbc-core/src/test/java/com/novarto/sanedbc/core/interpreter/AsyncDbInterpreterTest.java import com.novarto.lang.ConcurrentUtil; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.List; import junit.framework.AssertionFailedError; import org.hsqldb.jdbc.JDBCPool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.*; import static com.novarto.lang.testutil.TestUtil.tryTo; import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.lift; import static com.novarto.sanedbc.core.ops.Binders.NO_BINDER; import static fj.data.List.arrayList; import static fj.data.List.single; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; is(ex) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); SQLException noConn = new SQLException("no connection"); AsyncDbInterpreter noConnection = new AsyncDbInterpreter(() -> { throw noConn; }, executor); assertThat(awaitFailure(noConnection.transact(insert("alabala"))), is(noConn)); assertThat(awaitSuccess(dbi.submit(selectAll())), is(single("x"))); assertThat( awaitSuccess(dbi.transact(insert("y").bind(ignore -> insert("z")).map(ignore2 -> Unit.unit()))), is(Unit.unit()) ); assertThat(awaitSuccess(dbi.submit(selectAll())), is(arrayList("x", "y", "z"))); } private DB<Integer> insert(String x) { return new UpdateOp("INSERT INTO BAR VALUES(?)", ps -> ps.setString(1, x)); } private DB<List<String>> selectAll() {
return new SelectOp.FjList<>("SELECT * FROM BAR", NO_BINDER, rs -> rs.getString(1));
robertp1984/softwarecave
periodictable/src/test/java/com/example/periodictable/ws/access/PeriodicTableAccessWSTest.java
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // }
import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import org.dozer.DozerBeanMapper; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import static org.mockito.Matchers.anyInt; import org.mockito.Mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.MockitoAnnotations; import org.mockito.Spy;
package com.example.periodictable.ws.access; public class PeriodicTableAccessWSTest { @Mock
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // } // Path: periodictable/src/test/java/com/example/periodictable/ws/access/PeriodicTableAccessWSTest.java import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import org.dozer.DozerBeanMapper; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import static org.mockito.Matchers.anyInt; import org.mockito.Mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.MockitoAnnotations; import org.mockito.Spy; package com.example.periodictable.ws.access; public class PeriodicTableAccessWSTest { @Mock
private PeriodicTableService periodicTableService;
robertp1984/softwarecave
periodictable/src/test/java/com/example/periodictable/ws/access/PeriodicTableAccessWSTest.java
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // }
import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import org.dozer.DozerBeanMapper; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import static org.mockito.Matchers.anyInt; import org.mockito.Mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.MockitoAnnotations; import org.mockito.Spy;
package com.example.periodictable.ws.access; public class PeriodicTableAccessWSTest { @Mock private PeriodicTableService periodicTableService; @Spy private DozerBeanMapper mapper; @InjectMocks private PeriodicTableAccessWS periodicTableWS; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // } // Path: periodictable/src/test/java/com/example/periodictable/ws/access/PeriodicTableAccessWSTest.java import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import org.dozer.DozerBeanMapper; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import static org.mockito.Matchers.anyInt; import org.mockito.Mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.MockitoAnnotations; import org.mockito.Spy; package com.example.periodictable.ws.access; public class PeriodicTableAccessWSTest { @Mock private PeriodicTableService periodicTableService; @Spy private DozerBeanMapper mapper; @InjectMocks private PeriodicTableAccessWS periodicTableWS; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test
public void testGetElementByAtomicNumber() throws ElementNotFoundException, ElementNotFound_Exception {
robertp1984/softwarecave
periodictable/src/main/java/com/example/periodictable/ws/access/PeriodicTableAccessWS.java
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // }
import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import org.dozer.DozerBeanMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport;
package com.example.periodictable.ws.access; @WebService(name = "PeriodicTableAccess", targetNamespace = "http://www.example.org/periodictableaccess/") public class PeriodicTableAccessWS implements PeriodicTableAccess { private final Logger logger = LoggerFactory.getLogger(PeriodicTableAccessWS.class); @Autowired
// Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // } // Path: periodictable/src/main/java/com/example/periodictable/ws/access/PeriodicTableAccessWS.java import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import org.dozer.DozerBeanMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport; package com.example.periodictable.ws.access; @WebService(name = "PeriodicTableAccess", targetNamespace = "http://www.example.org/periodictableaccess/") public class PeriodicTableAccessWS implements PeriodicTableAccess { private final Logger logger = LoggerFactory.getLogger(PeriodicTableAccessWS.class); @Autowired
protected PeriodicTableService periodicTableService;
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/mbean/PersonList.java
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.model.SelectItem; import javax.inject.Named;
package com.example.people.ejb.mbean; @Named @SessionScoped public class PersonList implements Serializable { private static final long serialVersionUID = 3247324324234L; @EJB
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/mbean/PersonList.java import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.model.SelectItem; import javax.inject.Named; package com.example.people.ejb.mbean; @Named @SessionScoped public class PersonList implements Serializable { private static final long serialVersionUID = 3247324324234L; @EJB
private PersonRoleManager manager;
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/mbean/PersonList.java
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.model.SelectItem; import javax.inject.Named;
package com.example.people.ejb.mbean; @Named @SessionScoped public class PersonList implements Serializable { private static final long serialVersionUID = 3247324324234L; @EJB private PersonRoleManager manager; private String firstName; private String lastName; private int[] roleIds; // details support private int id;
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/mbean/PersonList.java import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Set; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.model.SelectItem; import javax.inject.Named; package com.example.people.ejb.mbean; @Named @SessionScoped public class PersonList implements Serializable { private static final long serialVersionUID = 3247324324234L; @EJB private PersonRoleManager manager; private String firstName; private String lastName; private int[] roleIds; // details support private int id;
private Set<Role> roles;
robertp1984/softwarecave
jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // }
import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named;
package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // } // Path: jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named; package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB
private PersonDAO personDAO;
robertp1984/softwarecave
jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // }
import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named;
package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB private PersonDAO personDAO;
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // } // Path: jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named; package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB private PersonDAO personDAO;
private Person newPerson;
robertp1984/softwarecave
jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // }
import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named;
package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB private PersonDAO personDAO; private Person newPerson; private List<Person> allPerson; public Person getNewPerson() { if (newPerson == null)
// Path: jpagenerators/src/main/java/com/example/jpagenerators/model/PersonDAO.java // @Stateless // public class PersonDAO { // // @PersistenceContext // private EntityManager em; // // public void addPerson(Person person) { // em.persist(person); // } // // public List<Person> getAllPerson() { // TypedQuery<Person> query = em.createNamedQuery("Person.selectAll", Person.class); // return query.getResultList(); // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Address.java // @Entity // @Table(name = "JPAGEN_ADDRESS") // public class Address implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, // generator = "addressGen") // @SequenceGenerator(name = "addressGen", // sequenceName = "JPAGEN_ADDRESS_SEQ") // private long id; // // @Column(name = "CITY") // private String city; // // @Column(name = "STREET") // private String street; // // protected Address() { // } // // public Address(String city, String street) { // this.city = city; // this.street = street; // } // // public long getId() { // return id; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // } // // Path: jpagenerators/src/main/java/com/example/jpagenerators/model/Person.java // @Entity // @Table(name = "JPAGEN_PERSON") // @NamedQuery(name = "Person.selectAll", // query = "select o from Person o order by o.id") // public class Person implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.TABLE, // generator = "personGen") // @TableGenerator(name = "personGen", // table = "JPAGEN_GENERATORS", // pkColumnName = "NAME", // pkColumnValue = "JPAGEN_PERSON_GEN", // valueColumnName = "VALUE") // private long id; // // @Column(name = "NAME") // private String name; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name = "ADDRESS_ID") // private Address address; // // protected Person() { // } // // public Person(String name, Address address) { // id = 0; // this.name = name; // this.address = address; // } // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // } // Path: jpagenerators/src/main/java/com/example/jpagenerators/view/PersonBean.java import com.example.jpagenerators.model.PersonDAO; import com.example.jpagenerators.model.Address; import com.example.jpagenerators.model.Person; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named; package com.example.jpagenerators.view; @Named @RequestScoped public class PersonBean { @EJB private PersonDAO personDAO; private Person newPerson; private List<Person> allPerson; public Person getNewPerson() { if (newPerson == null)
newPerson = new Person("", new Address("", ""));
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/PersonRoleManagerBean.java
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.entities.Person; import com.example.people.entities.Role; import java.util.List; import javax.ejb.Stateful; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery;
package com.example.people.ejb; @Stateful public class PersonRoleManagerBean implements PersonRoleManager { private static final long serialVersionUID = 234732489234234L; @PersistenceContext private EntityManager em; @Override
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/PersonRoleManagerBean.java import com.example.people.entities.Person; import com.example.people.entities.Role; import java.util.List; import javax.ejb.Stateful; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; package com.example.people.ejb; @Stateful public class PersonRoleManagerBean implements PersonRoleManager { private static final long serialVersionUID = 234732489234234L; @PersistenceContext private EntityManager em; @Override
public Person getPerson(int id) {
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/PersonRoleManagerBean.java
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.entities.Person; import com.example.people.entities.Role; import java.util.List; import javax.ejb.Stateful; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery;
package com.example.people.ejb; @Stateful public class PersonRoleManagerBean implements PersonRoleManager { private static final long serialVersionUID = 234732489234234L; @PersistenceContext private EntityManager em; @Override public Person getPerson(int id) { return em.find(Person.class, id); } @Override public void createPersonWithRoles(String firstName, String lastName, int[] roleIds) { Person person = new Person(firstName, lastName); setPersonRoles(person, roleIds); em.persist(person); } private void setPersonRoles(Person person, int[] roleIds) { person.clearRoles(); for (int roleId : roleIds) {
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/PersonRoleManagerBean.java import com.example.people.entities.Person; import com.example.people.entities.Role; import java.util.List; import javax.ejb.Stateful; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; package com.example.people.ejb; @Stateful public class PersonRoleManagerBean implements PersonRoleManager { private static final long serialVersionUID = 234732489234234L; @PersistenceContext private EntityManager em; @Override public Person getPerson(int id) { return em.find(Person.class, id); } @Override public void createPersonWithRoles(String firstName, String lastName, int[] roleIds) { Person person = new Person(firstName, lastName); setPersonRoles(person, roleIds); em.persist(person); } private void setPersonRoles(Person person, int[] roleIds) { person.clearRoles(); for (int roleId : roleIds) {
Role role = getRole(roleId);
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/mbean/RoleList.java
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named;
package com.example.people.ejb.mbean; @Named @SessionScoped public class RoleList implements Serializable { private static final long serialVersionUID = 234723894723432L; @EJB
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/mbean/RoleList.java import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; package com.example.people.ejb.mbean; @Named @SessionScoped public class RoleList implements Serializable { private static final long serialVersionUID = 234723894723432L; @EJB
private PersonRoleManager manager;
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/mbean/RoleList.java
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named;
description = ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String add() { if (!name.isEmpty() && !description.isEmpty()) manager.createRole(name, description); return backToList(); } public String backToList() { name = description = ""; return "back"; }
// Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java // @Remote // public interface PersonRoleManager extends Serializable { // void createPersonWithRoles(String firstName, String lastName, int[] roleIds); // Person getPerson(int id); // List<Person> getAllPersons(); // void deletePerson(int id); // void updatePerson(int id, String firstName, String lastName, int[] roleIds); // // void createRole(String name, String description); // Role getRole(int id); // List<Role> getAllRoles(); // void deleteRole(int id); // // long getPersonCountBelongingToRole(int roleId); // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/mbean/RoleList.java import com.example.people.ejb.PersonRoleManager; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; description = ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String add() { if (!name.isEmpty() && !description.isEmpty()) manager.createRole(name, description); return backToList(); } public String backToList() { name = description = ""; return "back"; }
public List<Role> getAllRoles() {
robertp1984/softwarecave
periodictable/src/main/java/com/example/periodictable/ws/admin/PeriodicTableAdminWS.java
// Path: periodictable/src/main/java/com/example/periodictable/ElementAlreadyExistsException.java // public class ElementAlreadyExistsException extends Exception { // // public ElementAlreadyExistsException(String msg) { // super(msg); // } // // public ElementAlreadyExistsException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/ElementCategoryNotFoundException.java // public class ElementCategoryNotFoundException extends Exception { // // public ElementCategoryNotFoundException(String msg) { // super(msg); // } // // public ElementCategoryNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // }
import com.example.periodictable.ElementAlreadyExistsException; import com.example.periodictable.ElementCategoryNotFoundException; import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import org.dozer.DozerBeanMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport;
package com.example.periodictable.ws.admin; @WebService(name = "PeriodicTableAdmin", targetNamespace = "http://www.example.org/periodictableadmin/") public class PeriodicTableAdminWS implements PeriodicTableAdmin { @Autowired
// Path: periodictable/src/main/java/com/example/periodictable/ElementAlreadyExistsException.java // public class ElementAlreadyExistsException extends Exception { // // public ElementAlreadyExistsException(String msg) { // super(msg); // } // // public ElementAlreadyExistsException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/ElementCategoryNotFoundException.java // public class ElementCategoryNotFoundException extends Exception { // // public ElementCategoryNotFoundException(String msg) { // super(msg); // } // // public ElementCategoryNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/ElementNotFoundException.java // public class ElementNotFoundException extends Exception { // // public ElementNotFoundException(String msg) { // super(msg); // } // // public ElementNotFoundException(String msg, Throwable cause) { // super(msg, cause); // } // // } // // Path: periodictable/src/main/java/com/example/periodictable/PeriodicTableService.java // @Service // @Transactional // public class PeriodicTableService { // // private final Logger logger = LoggerFactory.getLogger(PeriodicTableService.class); // // @PersistenceContext // private EntityManager em; // // // public List<Element> getElements() { // List<Element> list = em.createNamedQuery("findAllElements", Element.class).getResultList(); // return list; // } // // public Element getElementByAtomicNumber(int number) throws ElementNotFoundException { // try { // Element elem = em.createNamedQuery("findElementByAtomicNumber", Element.class) // .setParameter("atomicNumber", number).getSingleResult(); // return elem; // } catch (NoResultException e) { // throw new ElementNotFoundException(String.format("Element with atomicNumber=%s not found", number), e); // } // } // // public Element addElement(Element element) throws ElementCategoryNotFoundException, ElementAlreadyExistsException { // if (checkIfElementExists(element)) { // throw new ElementAlreadyExistsException(String.format("Element already exists")); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // element.setId(0); // element.setCategory(category); // em.persist(element); // return element; // } // // public boolean checkIfElementExists(Element element) { // List<Element> matchingElems = em.createNamedQuery("findElementByAtomicNumberOrNameOrSymbol", Element.class) // .setParameter("atomicNumber", element.getAtomicNumber()) // .setParameter("name", element.getName()) // .setParameter("symbol", element.getSymbol()) // .getResultList(); // return matchingElems.size() > 0; // } // // public void addElementInternal(Element element) { // logger.info("Adding element {}", element); // em.persist(element); // logger.info("Added element {} with ID={}", element, element.getId()); // } // // void addElementCategory(ElementCategory category) { // logger.info("Adding element category {}", category); // em.persist(category); // logger.info("Added element category {} with ID={}", category, category.getId()); // } // // public void updateElement(Element element) throws ElementCategoryNotFoundException, ElementNotFoundException { // Element elemDb = em.find(Element.class, element.getId()); // if (elemDb == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", element.getId())); // } // // int categoryId = element.getCategory().getId(); // ElementCategory category = em.find(ElementCategory.class, categoryId); // if (category == null) { // throw new ElementCategoryNotFoundException(String.format("Element category with id=%d not found", categoryId)); // } // // elemDb.setAtomicNumber(element.getAtomicNumber()); // elemDb.setName(element.getName()); // elemDb.setSymbol(element.getSymbol()); // elemDb.setCategory(category); // } // // public void removeElement(int id) throws ElementNotFoundException { // Element element = em.find(Element.class, id); // if (element == null) { // throw new ElementNotFoundException(String.format("Element with ID=%d not found", id)); // } // // em.remove(element); // } // } // Path: periodictable/src/main/java/com/example/periodictable/ws/admin/PeriodicTableAdminWS.java import com.example.periodictable.ElementAlreadyExistsException; import com.example.periodictable.ElementCategoryNotFoundException; import com.example.periodictable.ElementNotFoundException; import com.example.periodictable.PeriodicTableService; import com.example.periodictable.ws.common.Element; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import org.dozer.DozerBeanMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport; package com.example.periodictable.ws.admin; @WebService(name = "PeriodicTableAdmin", targetNamespace = "http://www.example.org/periodictableadmin/") public class PeriodicTableAdminWS implements PeriodicTableAdmin { @Autowired
private PeriodicTableService periodicTableService;
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/PersonRoleManager.java
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.Remote;
package com.example.people.ejb; @Remote public interface PersonRoleManager extends Serializable { void createPersonWithRoles(String firstName, String lastName, int[] roleIds);
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.Remote; package com.example.people.ejb; @Remote public interface PersonRoleManager extends Serializable { void createPersonWithRoles(String firstName, String lastName, int[] roleIds);
Person getPerson(int id);
robertp1984/softwarecave
people/src/main/java/com/example/people/ejb/PersonRoleManager.java
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // }
import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.Remote;
package com.example.people.ejb; @Remote public interface PersonRoleManager extends Serializable { void createPersonWithRoles(String firstName, String lastName, int[] roleIds); Person getPerson(int id); List<Person> getAllPersons(); void deletePerson(int id); void updatePerson(int id, String firstName, String lastName, int[] roleIds); void createRole(String name, String description);
// Path: people/src/main/java/com/example/people/entities/Person.java // @Entity // @Table(name = "PEOPLE_PERSON") // @NamedQueries({ // @NamedQuery(name = "selectAllPersons", query = "select o from Person o order by o.id"), // @NamedQuery(name = "selectAllPersonsForRole", query = "select o from Person o left join o.roles r where r.id=:roleId"), // @NamedQuery(name = "countPersonsForRole", query = "select count(o.id) from Person o left join o.roles r where r.id=:roleId") // }) // public class Person implements Serializable { // // private static final long serialVersionUID = -2346897234623746L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String firstName; // // @Column(nullable = false) // private String lastName; // // @ManyToMany // @JoinTable(name = "PEOPLE_PERSON_ROLE", // joinColumns = @JoinColumn(name = "PERSON_ID", referencedColumnName = "ID"), // inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")) // private Set<Role> roles; // // protected Person() { // } // // public Person(String firstName, String lastName) { // id = 0; // this.firstName = firstName; // this.lastName = lastName; // this.roles = new HashSet<>(); // } // // public int getId() { // return id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Role> getRoles() { // return Collections.unmodifiableSet(roles); // } // // public void addRole(Role role) { // this.roles.add(role); // } // // public void clearRoles() { // roles.clear(); // } // // @Override // public int hashCode() { // return Objects.hashCode(firstName) // ^ Objects.hashCode(lastName) // ^ Objects.hashCode(roles); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Person other = (Person) obj; // return Objects.equals(firstName, other.firstName) // && Objects.equals(lastName, other.lastName) // && Objects.equals(roles, other.roles); // } // // public int[] getRoleIds() { // int[] result = new int[roles.size()]; // int i = 0; // for (Role role : roles) { // result[i] = role.getId(); // i++; // } // return result; // } // // } // // Path: people/src/main/java/com/example/people/entities/Role.java // @Entity // @Table(name = "PEOPLE_ROLE") // @NamedQuery(name = "selectAllRoles", query = "select o from Role o order by o.id") // public class Role implements Serializable { // // private static final long serialVersionUID = 238947623894234L; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // @Column(nullable = false) // private String name; // // @Column(nullable = false) // private String description; // // protected Role() { // } // // public Role(String name, String description) { // id = 0; // this.name = name; // this.description = description; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int hashCode() { // return Objects.hashCode(name) ^ Objects.hashCode(description); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || getClass() != obj.getClass()) // return false; // // final Role other = (Role) obj; // return Objects.equals(this.name, other.name) // && Objects.equals(this.description, other.description); // } // // } // Path: people/src/main/java/com/example/people/ejb/PersonRoleManager.java import com.example.people.entities.Person; import com.example.people.entities.Role; import java.io.Serializable; import java.util.List; import javax.ejb.Remote; package com.example.people.ejb; @Remote public interface PersonRoleManager extends Serializable { void createPersonWithRoles(String firstName, String lastName, int[] roleIds); Person getPerson(int id); List<Person> getAllPersons(); void deletePerson(int id); void updatePerson(int id, String firstName, String lastName, int[] roleIds); void createRole(String name, String description);
Role getRole(int id);
callistaenterprise/blog-microservices
microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // }
import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors;
package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // Path: microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors; package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
public ProductAggregated(Product product, List<Recommendation> recommendations, List<Review> reviews, String serviceAddress) {
callistaenterprise/blog-microservices
microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // }
import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors;
package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // Path: microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors; package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
public ProductAggregated(Product product, List<Recommendation> recommendations, List<Review> reviews, String serviceAddress) {
callistaenterprise/blog-microservices
microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // }
import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors;
package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
// Path: util/src/main/java/se/callista/microservices/model/Product.java // public class Product { // private int productId; // private String name; // private int weight; // private String serviceAddress; // // public Product() { // } // // public Product(int productId, String name, int weight, String serviceAddress) { // this.productId = productId; // this.name = name; // this.weight = weight; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Recommendation.java // public class Recommendation { // private int productId; // private int recommendationId; // private String author; // private int rate; // private String content; // private String serviceAddress; // // public Recommendation() { // } // // public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) { // this.productId = productId; // this.recommendationId = recommendationId; // this.author = author; // this.rate = rate; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getRecommendationId() { // return recommendationId; // } // // public void setRecommendationId(int recommendationId) { // this.recommendationId = recommendationId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // // Path: util/src/main/java/se/callista/microservices/model/Review.java // public class Review { // private int productId; // private int reviewId; // private String author; // private String subject; // private String content; // private String serviceAddress; // // public Review() { // } // // public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) { // this.productId = productId; // this.reviewId = reviewId; // this.author = author; // this.subject = subject; // this.content = content; // this.serviceAddress = serviceAddress; // } // // public int getProductId() { // return productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public int getReviewId() { // return reviewId; // } // // public void setReviewId(int reviewId) { // this.reviewId = reviewId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getServiceAddress() { // return serviceAddress; // } // } // Path: microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/model/ProductAggregated.java import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import java.util.List; import java.util.stream.Collectors; package se.callista.microservices.composite.product.model; /** * Created by magnus on 04/03/15. */ public class ProductAggregated { private int productId; private String name; private int weight; private List<RecommendationSummary> recommendations; private List<ReviewSummary> reviews; private ServiceAddresses serviceAddresses;
public ProductAggregated(Product product, List<Recommendation> recommendations, List<Review> reviews, String serviceAddress) {
emergentdotorg/shaman
src/org/emergent/android/weave/AboutActivity.java
// Path: src/org/emergent/android/weave/util/Dbg.java // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // }
import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.text.TextUtils; import org.emergent.android.weave.util.Dbg.Log; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
text.setText(vPrefix + " " + version); text.setVisibility(View.VISIBLE); } TextView text = (TextView)findViewById(R.id.about_text_view); text.setText(readTextFromRawResource(R.raw.license_short)); } public static boolean showAbout(Activity activity) { Intent i = new Intent(activity, AboutActivity.class); activity.startActivity(i); return false; } private String readTextFromRawResource(int resourceid) { String license = ""; Resources resources = getResources(); BufferedReader in = new BufferedReader(new InputStreamReader(resources.openRawResource(resourceid))); String line; StringBuilder sb = new StringBuilder(); try { while ((line = in.readLine()) != null) { if (TextUtils.isEmpty(line)) { sb.append("\n\n"); } else { sb.append(line); sb.append(" "); } } license = sb.toString(); } catch (IOException e) {
// Path: src/org/emergent/android/weave/util/Dbg.java // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // } // Path: src/org/emergent/android/weave/AboutActivity.java import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.text.TextUtils; import org.emergent.android.weave.util.Dbg.Log; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; text.setText(vPrefix + " " + version); text.setVisibility(View.VISIBLE); } TextView text = (TextView)findViewById(R.id.about_text_view); text.setText(readTextFromRawResource(R.raw.license_short)); } public static boolean showAbout(Activity activity) { Intent i = new Intent(activity, AboutActivity.class); activity.startActivity(i); return false; } private String readTextFromRawResource(int resourceid) { String license = ""; Resources resources = getResources(); BufferedReader in = new BufferedReader(new InputStreamReader(resources.openRawResource(resourceid))); String line; StringBuilder sb = new StringBuilder(); try { while ((line = in.readLine()) != null) { if (TextUtils.isEmpty(line)) { sb.append("\n\n"); } else { sb.append(line); sb.append(" "); } } license = sb.toString(); } catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
emergentdotorg/shaman
src/org/emergent/android/weave/Constants.java
// Path: src/org/emergent/android/weave/util/Dbg.java // public class Dbg { // // static final String LOG_TAG = "EmergentWeave"; // // public static final String TAG = LOG_TAG; // // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // } // // // public static String getTag(Class clazz) { // // return LOG_TAG; // // } // // // // public static void logw(String msg) { // // Log.w(LOG_TAG, msg); // // } // // // // public static void logw(String pattern, Object... args) { // // String msg = String.format(pattern, args); // // Log.w(LOG_TAG, msg); // // } // // // // public static void trace(Object o, Class aClass, String methodName) { // // trace(o, aClass, methodName, null); // // } // // // // public static void trace(Object o, Class aClass, String methodName, String s) { // // String cName = (o != null) ? o.getClass().getSimpleName() : aClass.getSimpleName(); // // if (s == null) // // s = ""; // // String msg = String.format("trace: (%s.%s)%s", cName, methodName, s); // // Log.w(TAG, msg); // // } // // // // private static void println(String msg) { // // Log.i(LOG_TAG, msg); // // } // // // // private static void printf(String pattern, Object... args) { // // String msg = String.format(pattern, args); // // Log.i(LOG_TAG, msg); // // } // // // // private static void error(Throwable e) { // // Log.e(LOG_TAG, e.getMessage(), e); // // } // // // // private static void error(String message, Throwable e) { // // Log.e(LOG_TAG, message, e); // // } // }
import android.accounts.AccountManager; import org.emergent.android.weave.util.Dbg; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong;
private static final Properties sm_runtimeProps = new Properties(); private static final AtomicLong sm_runtimePropsLastReload = new AtomicLong(0); public static final boolean MENUITEM_HOME_DISABLED = ApiCompatUtil.IS_HONEYCOMB; public static Properties getRuntimeDefaults() { long lastReload = sm_runtimePropsLastReload.get(); if (RUNTIME_PROPS_FILE.isFile()) { long lastFileMod = RUNTIME_PROPS_FILE.lastModified(); if (lastFileMod > lastReload) { if (sm_runtimePropsLastReload.compareAndSet(lastReload, lastFileMod)) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(RUNTIME_PROPS_FILE)); sm_runtimeProps.clear(); sm_runtimeProps.load(is); } catch (Exception ignored) { } finally { if (is != null) try { is.close(); } catch (Exception ignored) { } } } } } return sm_runtimeProps; } public static interface Implementable {
// Path: src/org/emergent/android/weave/util/Dbg.java // public class Dbg { // // static final String LOG_TAG = "EmergentWeave"; // // public static final String TAG = LOG_TAG; // // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // } // // // public static String getTag(Class clazz) { // // return LOG_TAG; // // } // // // // public static void logw(String msg) { // // Log.w(LOG_TAG, msg); // // } // // // // public static void logw(String pattern, Object... args) { // // String msg = String.format(pattern, args); // // Log.w(LOG_TAG, msg); // // } // // // // public static void trace(Object o, Class aClass, String methodName) { // // trace(o, aClass, methodName, null); // // } // // // // public static void trace(Object o, Class aClass, String methodName, String s) { // // String cName = (o != null) ? o.getClass().getSimpleName() : aClass.getSimpleName(); // // if (s == null) // // s = ""; // // String msg = String.format("trace: (%s.%s)%s", cName, methodName, s); // // Log.w(TAG, msg); // // } // // // // private static void println(String msg) { // // Log.i(LOG_TAG, msg); // // } // // // // private static void printf(String pattern, Object... args) { // // String msg = String.format(pattern, args); // // Log.i(LOG_TAG, msg); // // } // // // // private static void error(Throwable e) { // // Log.e(LOG_TAG, e.getMessage(), e); // // } // // // // private static void error(String message, Throwable e) { // // Log.e(LOG_TAG, message, e); // // } // } // Path: src/org/emergent/android/weave/Constants.java import android.accounts.AccountManager; import org.emergent.android.weave.util.Dbg; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong; private static final Properties sm_runtimeProps = new Properties(); private static final AtomicLong sm_runtimePropsLastReload = new AtomicLong(0); public static final boolean MENUITEM_HOME_DISABLED = ApiCompatUtil.IS_HONEYCOMB; public static Properties getRuntimeDefaults() { long lastReload = sm_runtimePropsLastReload.get(); if (RUNTIME_PROPS_FILE.isFile()) { long lastFileMod = RUNTIME_PROPS_FILE.lastModified(); if (lastFileMod > lastReload) { if (sm_runtimePropsLastReload.compareAndSet(lastReload, lastFileMod)) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(RUNTIME_PROPS_FILE)); sm_runtimeProps.clear(); sm_runtimeProps.load(is); } catch (Exception ignored) { } finally { if (is != null) try { is.close(); } catch (Exception ignored) { } } } } } return sm_runtimeProps; } public static interface Implementable {
public static final String TAG = Dbg.TAG;
emergentdotorg/shaman
src/org/emergent/android/weave/persistence/Weaves.java
// Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/WeaveBasicObject.java // public class WeaveBasicObject { // // private URI m_uri = null; // private final URI m_queryUri; // private final JSONObject m_nodeObj; // // public WeaveBasicObject(URI queryUri, JSONObject nodeObj) { // m_queryUri = queryUri; // m_nodeObj = nodeObj; // } // // public String getId() throws JSONException { // return m_nodeObj.getString("id"); // } // // public String getSortIndex() throws JSONException { // return m_nodeObj.getString("sortindex"); // } // // public String getModified() throws JSONException { // return m_nodeObj.getString("modified"); // } // // public Date getModifiedDate() throws JSONException { // return WeaveUtil.toModifiedTimeDate(getModified()); // } // // public URI getUri() throws JSONException { // if (m_uri == null) { // try { // String baseUriStr = m_queryUri.toASCIIString(); // String queryPart = m_queryUri.getRawQuery(); // if (queryPart != null) // baseUriStr = baseUriStr.substring(0, baseUriStr.indexOf(queryPart) - 1); // if (!baseUriStr.endsWith("/")) // baseUriStr += "/"; // String nodeUriStr = baseUriStr + new URI(null,null,getId(), null).toASCIIString(); // m_uri = new URI(nodeUriStr); // } catch (URISyntaxException e) { // throw new JSONException(e.getMessage()); // } // } // return m_uri; // } // // public JSONObject getPayload() throws JSONException { // return new JSONObject(m_nodeObj.getString("payload")); // } // // public JSONObject getEncryptedPayload(BulkKeyTool bulkTool) throws JSONException, IOException, WeaveException { // return getEncryptedPayload(bulkTool.getBulkKeyCouplet()); // } // // private JSONObject getEncryptedPayload(BulkKeyCouplet bulkKeyPair) throws JSONException, IOException, WeaveException { // try { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKeyPair); // } catch (GeneralSecurityException e) { // throw new WeaveException(e); // } // } // // // public JSONObject getEncryptedPayload(Key bulkKey, Key hmacKey) // throws JSONException, IOException, GeneralSecurityException, WeaveException { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKey, hmacKey); // } // // public JSONObject toJSONObject() { // return m_nodeObj; // } // // public String toJSONObjectString() throws JSONException { // return toJSONObject().toString(0); // } // // public static class WeaveEncryptedObject { // // private final JSONObject m_nodeObj; // // public WeaveEncryptedObject(JSONObject nodeObj) { // m_nodeObj = nodeObj; // } // // public String getHmac() throws JSONException { // return m_nodeObj.getString("hmac"); // } // // public String getCiphertext() throws JSONException { // return m_nodeObj.getString("ciphertext"); // } // // public String getIv() throws JSONException { // return m_nodeObj.getString("IV"); // } // // public JSONObject decryptObject(BulkKeyCouplet keyPair) throws GeneralSecurityException, JSONException { // return decryptObject(keyPair.cipherKey, keyPair.hmacKey); // } // // public JSONObject decryptObject(Key key, Key hmacKey) throws GeneralSecurityException, JSONException { // String plaintext = WeaveCryptoUtil.getInstance().decrypt(key, hmacKey, getCiphertext(), getIv(), getHmac()); // return new JSONObject(plaintext); // } // } // }
import org.emergent.android.weave.client.CollectionNode; import org.emergent.android.weave.client.WeaveBasicObject; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.BaseColumns; import java.util.Date; import java.util.List;
package org.emergent.android.weave.persistence; /** * @author Patrick Woodworth */ public class Weaves { public static void setBasicContentValues(ContentValues values, Record info) throws JSONException { boolean isDeleted = info.isDeleted(); putColumnValue(values, Columns.UUID, info.getId()); putColumnValue(values, Columns.IS_DELETED, isDeleted); putColumnValue(values, Columns.LAST_MODIFIED, info.getModifiedInSeconds()); } public static void putColumnValue(ContentValues values, String colName, String value) { values.put(colName, value); } public static void putColumnValue(ContentValues values, String colName, long value) { values.put(colName, value); } public static void putColumnValue(ContentValues values, String colName, boolean value) { values.put(colName, value); } public static class Columns implements BaseColumns { // BaseColumn contains _id. public static final String UUID = "uuid"; public static final String SORT_INDEX = "sortIndex"; public static final String LAST_MODIFIED = "lastModified"; public static final String IS_DELETED = "isDeleted"; } public static abstract class Updater { private final Uri m_authority;
// Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/WeaveBasicObject.java // public class WeaveBasicObject { // // private URI m_uri = null; // private final URI m_queryUri; // private final JSONObject m_nodeObj; // // public WeaveBasicObject(URI queryUri, JSONObject nodeObj) { // m_queryUri = queryUri; // m_nodeObj = nodeObj; // } // // public String getId() throws JSONException { // return m_nodeObj.getString("id"); // } // // public String getSortIndex() throws JSONException { // return m_nodeObj.getString("sortindex"); // } // // public String getModified() throws JSONException { // return m_nodeObj.getString("modified"); // } // // public Date getModifiedDate() throws JSONException { // return WeaveUtil.toModifiedTimeDate(getModified()); // } // // public URI getUri() throws JSONException { // if (m_uri == null) { // try { // String baseUriStr = m_queryUri.toASCIIString(); // String queryPart = m_queryUri.getRawQuery(); // if (queryPart != null) // baseUriStr = baseUriStr.substring(0, baseUriStr.indexOf(queryPart) - 1); // if (!baseUriStr.endsWith("/")) // baseUriStr += "/"; // String nodeUriStr = baseUriStr + new URI(null,null,getId(), null).toASCIIString(); // m_uri = new URI(nodeUriStr); // } catch (URISyntaxException e) { // throw new JSONException(e.getMessage()); // } // } // return m_uri; // } // // public JSONObject getPayload() throws JSONException { // return new JSONObject(m_nodeObj.getString("payload")); // } // // public JSONObject getEncryptedPayload(BulkKeyTool bulkTool) throws JSONException, IOException, WeaveException { // return getEncryptedPayload(bulkTool.getBulkKeyCouplet()); // } // // private JSONObject getEncryptedPayload(BulkKeyCouplet bulkKeyPair) throws JSONException, IOException, WeaveException { // try { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKeyPair); // } catch (GeneralSecurityException e) { // throw new WeaveException(e); // } // } // // // public JSONObject getEncryptedPayload(Key bulkKey, Key hmacKey) // throws JSONException, IOException, GeneralSecurityException, WeaveException { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKey, hmacKey); // } // // public JSONObject toJSONObject() { // return m_nodeObj; // } // // public String toJSONObjectString() throws JSONException { // return toJSONObject().toString(0); // } // // public static class WeaveEncryptedObject { // // private final JSONObject m_nodeObj; // // public WeaveEncryptedObject(JSONObject nodeObj) { // m_nodeObj = nodeObj; // } // // public String getHmac() throws JSONException { // return m_nodeObj.getString("hmac"); // } // // public String getCiphertext() throws JSONException { // return m_nodeObj.getString("ciphertext"); // } // // public String getIv() throws JSONException { // return m_nodeObj.getString("IV"); // } // // public JSONObject decryptObject(BulkKeyCouplet keyPair) throws GeneralSecurityException, JSONException { // return decryptObject(keyPair.cipherKey, keyPair.hmacKey); // } // // public JSONObject decryptObject(Key key, Key hmacKey) throws GeneralSecurityException, JSONException { // String plaintext = WeaveCryptoUtil.getInstance().decrypt(key, hmacKey, getCiphertext(), getIv(), getHmac()); // return new JSONObject(plaintext); // } // } // } // Path: src/org/emergent/android/weave/persistence/Weaves.java import org.emergent.android.weave.client.CollectionNode; import org.emergent.android.weave.client.WeaveBasicObject; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.BaseColumns; import java.util.Date; import java.util.List; package org.emergent.android.weave.persistence; /** * @author Patrick Woodworth */ public class Weaves { public static void setBasicContentValues(ContentValues values, Record info) throws JSONException { boolean isDeleted = info.isDeleted(); putColumnValue(values, Columns.UUID, info.getId()); putColumnValue(values, Columns.IS_DELETED, isDeleted); putColumnValue(values, Columns.LAST_MODIFIED, info.getModifiedInSeconds()); } public static void putColumnValue(ContentValues values, String colName, String value) { values.put(colName, value); } public static void putColumnValue(ContentValues values, String colName, long value) { values.put(colName, value); } public static void putColumnValue(ContentValues values, String colName, boolean value) { values.put(colName, value); } public static class Columns implements BaseColumns { // BaseColumn contains _id. public static final String UUID = "uuid"; public static final String SORT_INDEX = "sortIndex"; public static final String LAST_MODIFIED = "lastModified"; public static final String IS_DELETED = "isDeleted"; } public static abstract class Updater { private final Uri m_authority;
private final CollectionNode m_collectionNode;
emergentdotorg/shaman
src/org/emergent/android/weave/persistence/Weaves.java
// Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/WeaveBasicObject.java // public class WeaveBasicObject { // // private URI m_uri = null; // private final URI m_queryUri; // private final JSONObject m_nodeObj; // // public WeaveBasicObject(URI queryUri, JSONObject nodeObj) { // m_queryUri = queryUri; // m_nodeObj = nodeObj; // } // // public String getId() throws JSONException { // return m_nodeObj.getString("id"); // } // // public String getSortIndex() throws JSONException { // return m_nodeObj.getString("sortindex"); // } // // public String getModified() throws JSONException { // return m_nodeObj.getString("modified"); // } // // public Date getModifiedDate() throws JSONException { // return WeaveUtil.toModifiedTimeDate(getModified()); // } // // public URI getUri() throws JSONException { // if (m_uri == null) { // try { // String baseUriStr = m_queryUri.toASCIIString(); // String queryPart = m_queryUri.getRawQuery(); // if (queryPart != null) // baseUriStr = baseUriStr.substring(0, baseUriStr.indexOf(queryPart) - 1); // if (!baseUriStr.endsWith("/")) // baseUriStr += "/"; // String nodeUriStr = baseUriStr + new URI(null,null,getId(), null).toASCIIString(); // m_uri = new URI(nodeUriStr); // } catch (URISyntaxException e) { // throw new JSONException(e.getMessage()); // } // } // return m_uri; // } // // public JSONObject getPayload() throws JSONException { // return new JSONObject(m_nodeObj.getString("payload")); // } // // public JSONObject getEncryptedPayload(BulkKeyTool bulkTool) throws JSONException, IOException, WeaveException { // return getEncryptedPayload(bulkTool.getBulkKeyCouplet()); // } // // private JSONObject getEncryptedPayload(BulkKeyCouplet bulkKeyPair) throws JSONException, IOException, WeaveException { // try { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKeyPair); // } catch (GeneralSecurityException e) { // throw new WeaveException(e); // } // } // // // public JSONObject getEncryptedPayload(Key bulkKey, Key hmacKey) // throws JSONException, IOException, GeneralSecurityException, WeaveException { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKey, hmacKey); // } // // public JSONObject toJSONObject() { // return m_nodeObj; // } // // public String toJSONObjectString() throws JSONException { // return toJSONObject().toString(0); // } // // public static class WeaveEncryptedObject { // // private final JSONObject m_nodeObj; // // public WeaveEncryptedObject(JSONObject nodeObj) { // m_nodeObj = nodeObj; // } // // public String getHmac() throws JSONException { // return m_nodeObj.getString("hmac"); // } // // public String getCiphertext() throws JSONException { // return m_nodeObj.getString("ciphertext"); // } // // public String getIv() throws JSONException { // return m_nodeObj.getString("IV"); // } // // public JSONObject decryptObject(BulkKeyCouplet keyPair) throws GeneralSecurityException, JSONException { // return decryptObject(keyPair.cipherKey, keyPair.hmacKey); // } // // public JSONObject decryptObject(Key key, Key hmacKey) throws GeneralSecurityException, JSONException { // String plaintext = WeaveCryptoUtil.getInstance().decrypt(key, hmacKey, getCiphertext(), getIv(), getHmac()); // return new JSONObject(plaintext); // } // } // }
import org.emergent.android.weave.client.CollectionNode; import org.emergent.android.weave.client.WeaveBasicObject; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.BaseColumns; import java.util.Date; import java.util.List;
public int deleteRecords(ContentResolver cResolver) { return cResolver.delete(m_authority, "", new String[] {} ); } public void insertRecord(ContentResolver cResolver, Record info) throws JSONException { ContentValues values = new ContentValues(); setContentValues(values, info); cResolver.insert(m_authority, values); } public int insertRecords(ContentResolver cResolver, List<Record> infos) throws JSONException { ContentValues[] valuesArray = new ContentValues[infos.size()]; int ii = 0; for (Record info : infos) { ContentValues values = new ContentValues(); setContentValues(values, info); valuesArray[ii++] = values; } return cResolver.bulkInsert(m_authority, valuesArray); } protected abstract void setContentValues(ContentValues values, Record info) throws JSONException; } /** * @author Patrick Woodworth */ public static class Record {
// Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/WeaveBasicObject.java // public class WeaveBasicObject { // // private URI m_uri = null; // private final URI m_queryUri; // private final JSONObject m_nodeObj; // // public WeaveBasicObject(URI queryUri, JSONObject nodeObj) { // m_queryUri = queryUri; // m_nodeObj = nodeObj; // } // // public String getId() throws JSONException { // return m_nodeObj.getString("id"); // } // // public String getSortIndex() throws JSONException { // return m_nodeObj.getString("sortindex"); // } // // public String getModified() throws JSONException { // return m_nodeObj.getString("modified"); // } // // public Date getModifiedDate() throws JSONException { // return WeaveUtil.toModifiedTimeDate(getModified()); // } // // public URI getUri() throws JSONException { // if (m_uri == null) { // try { // String baseUriStr = m_queryUri.toASCIIString(); // String queryPart = m_queryUri.getRawQuery(); // if (queryPart != null) // baseUriStr = baseUriStr.substring(0, baseUriStr.indexOf(queryPart) - 1); // if (!baseUriStr.endsWith("/")) // baseUriStr += "/"; // String nodeUriStr = baseUriStr + new URI(null,null,getId(), null).toASCIIString(); // m_uri = new URI(nodeUriStr); // } catch (URISyntaxException e) { // throw new JSONException(e.getMessage()); // } // } // return m_uri; // } // // public JSONObject getPayload() throws JSONException { // return new JSONObject(m_nodeObj.getString("payload")); // } // // public JSONObject getEncryptedPayload(BulkKeyTool bulkTool) throws JSONException, IOException, WeaveException { // return getEncryptedPayload(bulkTool.getBulkKeyCouplet()); // } // // private JSONObject getEncryptedPayload(BulkKeyCouplet bulkKeyPair) throws JSONException, IOException, WeaveException { // try { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKeyPair); // } catch (GeneralSecurityException e) { // throw new WeaveException(e); // } // } // // // public JSONObject getEncryptedPayload(Key bulkKey, Key hmacKey) // throws JSONException, IOException, GeneralSecurityException, WeaveException { // WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); // return weo.decryptObject(bulkKey, hmacKey); // } // // public JSONObject toJSONObject() { // return m_nodeObj; // } // // public String toJSONObjectString() throws JSONException { // return toJSONObject().toString(0); // } // // public static class WeaveEncryptedObject { // // private final JSONObject m_nodeObj; // // public WeaveEncryptedObject(JSONObject nodeObj) { // m_nodeObj = nodeObj; // } // // public String getHmac() throws JSONException { // return m_nodeObj.getString("hmac"); // } // // public String getCiphertext() throws JSONException { // return m_nodeObj.getString("ciphertext"); // } // // public String getIv() throws JSONException { // return m_nodeObj.getString("IV"); // } // // public JSONObject decryptObject(BulkKeyCouplet keyPair) throws GeneralSecurityException, JSONException { // return decryptObject(keyPair.cipherKey, keyPair.hmacKey); // } // // public JSONObject decryptObject(Key key, Key hmacKey) throws GeneralSecurityException, JSONException { // String plaintext = WeaveCryptoUtil.getInstance().decrypt(key, hmacKey, getCiphertext(), getIv(), getHmac()); // return new JSONObject(plaintext); // } // } // } // Path: src/org/emergent/android/weave/persistence/Weaves.java import org.emergent.android.weave.client.CollectionNode; import org.emergent.android.weave.client.WeaveBasicObject; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.BaseColumns; import java.util.Date; import java.util.List; public int deleteRecords(ContentResolver cResolver) { return cResolver.delete(m_authority, "", new String[] {} ); } public void insertRecord(ContentResolver cResolver, Record info) throws JSONException { ContentValues values = new ContentValues(); setContentValues(values, info); cResolver.insert(m_authority, values); } public int insertRecords(ContentResolver cResolver, List<Record> infos) throws JSONException { ContentValues[] valuesArray = new ContentValues[infos.size()]; int ii = 0; for (Record info : infos) { ContentValues values = new ContentValues(); setContentValues(values, info); valuesArray[ii++] = values; } return cResolver.bulkInsert(m_authority, valuesArray); } protected abstract void setContentValues(ContentValues values, Record info) throws JSONException; } /** * @author Patrick Woodworth */ public static class Record {
private WeaveBasicObject m_wbo;
emergentdotorg/shaman
weave/server/src/main/java/org/emergent/plumber/util/DumpFilter.java
// Path: weave/server/src/main/java/org/emergent/plumber/MiscUtil.java // public class MiscUtil { // // public static void dumpRequestParameters(GenericServlet servlet, HttpServletRequest req) { // for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) { // String parmName = (String)enu.nextElement(); // String parmValue = req.getParameter(parmName); // servlet.log(String.format("parm : %s = %s", parmName, parmValue)); // } // } // // public static String toWeaveTimestamp(long millis) { // return String.format("%.2f", millis / 1000.0); // } // // public static double toWeaveTimestampDouble(long millis) { // return (millis / 10) / 100.0; // } // // public static String readBody(HttpServletRequest req) throws IOException { // BufferedReader reader = req.getReader(); // StringWriter writer = new StringWriter(); // String line = ""; // while ((line = reader.readLine()) != null) { // writer.write(line); // // writer.write("\n"); // } // return writer.toString(); // } // // public static boolean isEmpty(String s) { // return (s == null || s.trim().length() == 0); // } // // public static void close(InputStream closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(OutputStream closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Reader closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Writer closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Connection closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Statement closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(ResultSet closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void copy(InputStream is, OutputStream os) throws IOException { // byte buf[] = new byte[1024]; // int letti; // while ((letti = is.read(buf)) > 0) { // os.write(buf, 0, letti); // } // } // }
import org.emergent.plumber.MiscUtil; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter;
if (!(servletRequest instanceof HttpServletRequest)) { filterChain.doFilter(servletRequest, servletResponse); return; } PrintStream ds = null; try { ds = getDumpStream(); HttpServletRequest httpRequest = (HttpServletRequest)servletRequest; HttpServletResponse httpResponse = (HttpServletResponse)servletResponse; if (m_dumpRequest) { ServletUtil.doFilter2(httpRequest, ds); MyRequestWrapper bufferedRequest = new MyRequestWrapper(httpRequest); httpRequest = bufferedRequest; String body = bufferedRequest.getBody(); ds.println("REQUEST -> " + body); } if (m_dumpResponse) { MyResponseWrapper wrappedResp = new MyResponseWrapper(httpResponse); filterChain.doFilter(httpRequest, wrappedResp); String body = wrappedResp.getBody(); ds.println("RESPONSE -> " + body); } else { filterChain.doFilter(httpRequest, httpResponse); } } finally { if (m_dumpFile != null) {
// Path: weave/server/src/main/java/org/emergent/plumber/MiscUtil.java // public class MiscUtil { // // public static void dumpRequestParameters(GenericServlet servlet, HttpServletRequest req) { // for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) { // String parmName = (String)enu.nextElement(); // String parmValue = req.getParameter(parmName); // servlet.log(String.format("parm : %s = %s", parmName, parmValue)); // } // } // // public static String toWeaveTimestamp(long millis) { // return String.format("%.2f", millis / 1000.0); // } // // public static double toWeaveTimestampDouble(long millis) { // return (millis / 10) / 100.0; // } // // public static String readBody(HttpServletRequest req) throws IOException { // BufferedReader reader = req.getReader(); // StringWriter writer = new StringWriter(); // String line = ""; // while ((line = reader.readLine()) != null) { // writer.write(line); // // writer.write("\n"); // } // return writer.toString(); // } // // public static boolean isEmpty(String s) { // return (s == null || s.trim().length() == 0); // } // // public static void close(InputStream closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(OutputStream closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Reader closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Writer closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Connection closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(Statement closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void close(ResultSet closeable) { // if (closeable != null) try { // closeable.close(); // } catch (Exception ignored) { // } // } // // public static void copy(InputStream is, OutputStream os) throws IOException { // byte buf[] = new byte[1024]; // int letti; // while ((letti = is.read(buf)) > 0) { // os.write(buf, 0, letti); // } // } // } // Path: weave/server/src/main/java/org/emergent/plumber/util/DumpFilter.java import org.emergent.plumber.MiscUtil; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; if (!(servletRequest instanceof HttpServletRequest)) { filterChain.doFilter(servletRequest, servletResponse); return; } PrintStream ds = null; try { ds = getDumpStream(); HttpServletRequest httpRequest = (HttpServletRequest)servletRequest; HttpServletResponse httpResponse = (HttpServletResponse)servletResponse; if (m_dumpRequest) { ServletUtil.doFilter2(httpRequest, ds); MyRequestWrapper bufferedRequest = new MyRequestWrapper(httpRequest); httpRequest = bufferedRequest; String body = bufferedRequest.getBody(); ds.println("REQUEST -> " + body); } if (m_dumpResponse) { MyResponseWrapper wrappedResp = new MyResponseWrapper(httpResponse); filterChain.doFilter(httpRequest, wrappedResp); String body = wrappedResp.getBody(); ds.println("RESPONSE -> " + body); } else { filterChain.doFilter(httpRequest, httpResponse); } } finally { if (m_dumpFile != null) {
MiscUtil.close(ds);
emergentdotorg/shaman
src/org/emergent/android/weave/ShamanApplication.java
// Path: src/org/emergent/android/weave/util/Dbg.java // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // }
import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import org.emergent.android.weave.util.Dbg.Log; import java.io.File;
/* * Copyright 2012 Patrick Woodworth * * 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 org.emergent.android.weave; /** * @author Patrick Woodworth */ public class ShamanApplication extends Application implements Constants.Implementable { private static ShamanApplication sm_instance; @Override public void onCreate() { super.onCreate(); sm_instance = this; } public static ShamanApplication getInstance() { return sm_instance; } public static String getApplicationName() { String retval = "?"; try { Context context = getInstance(); String pkgName = context.getPackageName(); PackageInfo pInfo = context.getPackageManager().getPackageInfo(pkgName, 0); retval = context.getString(pInfo.applicationInfo.labelRes); } catch (PackageManager.NameNotFoundException e) {
// Path: src/org/emergent/android/weave/util/Dbg.java // @SuppressWarnings("ConstantConditions") // public static class Log { // // private static final int SHAMAN_LOG_LEVEL = android.util.Log.INFO; // // public static void v(String tag, String msg) { // if (android.util.Log.VERBOSE >= SHAMAN_LOG_LEVEL) android.util.Log.v(tag, msg); // } // // public static void d(String tag, String msg) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg); // } // // public static void d(String tag, String msg, Throwable tr) { // if (android.util.Log.DEBUG >= SHAMAN_LOG_LEVEL) android.util.Log.d(tag, msg, tr); // } // // public static void i(String tag, String msg) { // if (android.util.Log.INFO >= SHAMAN_LOG_LEVEL) android.util.Log.i(tag, msg); // } // // public static void w(String tag, String msg) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg); // } // // public static void w(String tag, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, tr); // } // // public static void w(String tag, String msg, Throwable tr) { // if (android.util.Log.WARN >= SHAMAN_LOG_LEVEL) android.util.Log.w(tag, msg, tr); // } // // public static void e(String tag, String msg) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg); // } // // public static void e(String tag, String msg, Throwable tr) { // if (android.util.Log.ERROR >= SHAMAN_LOG_LEVEL) android.util.Log.e(tag, msg, tr); // } // } // Path: src/org/emergent/android/weave/ShamanApplication.java import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import org.emergent.android.weave.util.Dbg.Log; import java.io.File; /* * Copyright 2012 Patrick Woodworth * * 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 org.emergent.android.weave; /** * @author Patrick Woodworth */ public class ShamanApplication extends Application implements Constants.Implementable { private static ShamanApplication sm_instance; @Override public void onCreate() { super.onCreate(); sm_instance = this; } public static ShamanApplication getInstance() { return sm_instance; } public static String getApplicationName() { String retval = "?"; try { Context context = getInstance(); String pkgName = context.getPackageName(); PackageInfo pInfo = context.getPackageManager().getPackageInfo(pkgName, 0); retval = context.getString(pInfo.applicationInfo.labelRes); } catch (PackageManager.NameNotFoundException e) {
Log.e(StaticUtils.TAG, "Application name not found!", e);
emergentdotorg/shaman
src/org/emergent/android/weave/persistence/Passwords.java
// Path: src/org/emergent/android/weave/Constants.java // public class Constants { // // public static final String APP_PACKAGE_NAME = Constants.class.getPackage().getName(); // // public static final String BOOKMARK_PROVIDER_AUTHORITY = "org.emergent.android.weave.bookmarkcontentprovider"; // // public static final String PASSWORD_PROVIDER_AUTHORITY = "org.emergent.android.weave.passwordcontentprovider"; // // public static final int EDIT_ACCOUNT_LOGIN_REQUEST_CODE = 1000; // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "org.emergent.android.weave"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "org.emergent.android.weave"; // // public static final String USERDATA_USERNAME_KEY = AccountManager.KEY_ACCOUNT_NAME; // // public static final String USERDATA_PASSWORD_KEY = AccountManager.KEY_PASSWORD; // // public static final String USERDATA_SERVER_KEY = "server_url"; // // public static final String USERDATA_SECRET_KEY = "sync_key"; // // public static final String ROW_ID_INTENT_EXTRA_KEY = APP_PACKAGE_NAME + ".rowId"; // // public static final int SYNC_EVENT = 1; // // static final boolean MENUITEM_HELP_DISABLED = true; // static final boolean MENUITEM_RESET_DISABLED = false; // static final boolean MENUITEM_SETTINGS_DISABLED = true; // // private static final String RUNTIME_PROPERTIES_PATH = "/sdcard/weave.properties"; // // private static final File RUNTIME_PROPS_FILE = new File(RUNTIME_PROPERTIES_PATH); // // private static final Properties sm_runtimeProps = new Properties(); // // private static final AtomicLong sm_runtimePropsLastReload = new AtomicLong(0); // public static final boolean MENUITEM_HOME_DISABLED = ApiCompatUtil.IS_HONEYCOMB; // // // public static Properties getRuntimeDefaults() { // long lastReload = sm_runtimePropsLastReload.get(); // if (RUNTIME_PROPS_FILE.isFile()) { // long lastFileMod = RUNTIME_PROPS_FILE.lastModified(); // if (lastFileMod > lastReload) { // if (sm_runtimePropsLastReload.compareAndSet(lastReload, lastFileMod)) { // InputStream is = null; // try { // is = new BufferedInputStream(new FileInputStream(RUNTIME_PROPS_FILE)); // sm_runtimeProps.clear(); // sm_runtimeProps.load(is); // } catch (Exception ignored) { // } finally { // if (is != null) try { is.close(); } catch (Exception ignored) { } // } // } // } // } // return sm_runtimeProps; // } // // public static interface Implementable { // // public static final String TAG = Dbg.TAG; // String FRAG_TAG_BUNDLE_KEY = "fragTag"; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // }
import android.content.ContentValues; import android.net.Uri; import org.emergent.android.weave.Constants; import org.emergent.android.weave.client.CollectionNode; import org.json.JSONException;
/* * Copyright 2010 Patrick Woodworth * * 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 org.emergent.android.weave.persistence; /** * @author Patrick Woodworth */ public class Passwords { public static final String AUTHORITY = Constants.PASSWORD_PROVIDER_AUTHORITY; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); public static final Weaves.Updater UPDATER =
// Path: src/org/emergent/android/weave/Constants.java // public class Constants { // // public static final String APP_PACKAGE_NAME = Constants.class.getPackage().getName(); // // public static final String BOOKMARK_PROVIDER_AUTHORITY = "org.emergent.android.weave.bookmarkcontentprovider"; // // public static final String PASSWORD_PROVIDER_AUTHORITY = "org.emergent.android.weave.passwordcontentprovider"; // // public static final int EDIT_ACCOUNT_LOGIN_REQUEST_CODE = 1000; // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "org.emergent.android.weave"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "org.emergent.android.weave"; // // public static final String USERDATA_USERNAME_KEY = AccountManager.KEY_ACCOUNT_NAME; // // public static final String USERDATA_PASSWORD_KEY = AccountManager.KEY_PASSWORD; // // public static final String USERDATA_SERVER_KEY = "server_url"; // // public static final String USERDATA_SECRET_KEY = "sync_key"; // // public static final String ROW_ID_INTENT_EXTRA_KEY = APP_PACKAGE_NAME + ".rowId"; // // public static final int SYNC_EVENT = 1; // // static final boolean MENUITEM_HELP_DISABLED = true; // static final boolean MENUITEM_RESET_DISABLED = false; // static final boolean MENUITEM_SETTINGS_DISABLED = true; // // private static final String RUNTIME_PROPERTIES_PATH = "/sdcard/weave.properties"; // // private static final File RUNTIME_PROPS_FILE = new File(RUNTIME_PROPERTIES_PATH); // // private static final Properties sm_runtimeProps = new Properties(); // // private static final AtomicLong sm_runtimePropsLastReload = new AtomicLong(0); // public static final boolean MENUITEM_HOME_DISABLED = ApiCompatUtil.IS_HONEYCOMB; // // // public static Properties getRuntimeDefaults() { // long lastReload = sm_runtimePropsLastReload.get(); // if (RUNTIME_PROPS_FILE.isFile()) { // long lastFileMod = RUNTIME_PROPS_FILE.lastModified(); // if (lastFileMod > lastReload) { // if (sm_runtimePropsLastReload.compareAndSet(lastReload, lastFileMod)) { // InputStream is = null; // try { // is = new BufferedInputStream(new FileInputStream(RUNTIME_PROPS_FILE)); // sm_runtimeProps.clear(); // sm_runtimeProps.load(is); // } catch (Exception ignored) { // } finally { // if (is != null) try { is.close(); } catch (Exception ignored) { } // } // } // } // } // return sm_runtimeProps; // } // // public static interface Implementable { // // public static final String TAG = Dbg.TAG; // String FRAG_TAG_BUNDLE_KEY = "fragTag"; // } // } // // Path: weave/client/src/main/java/org/emergent/android/weave/client/CollectionNode.java // public enum CollectionNode { // // STORAGE_CLIENTS("clients"), // STORAGE_BOOKMARKS("bookmarks"), // STORAGE_PASSWORDS("passwords"), // ; // // public final String engineName; // public final String nodePath; // // CollectionNode(String engineName) { // this.engineName = engineName; // this.nodePath = "/storage/" + this.engineName; // } // } // Path: src/org/emergent/android/weave/persistence/Passwords.java import android.content.ContentValues; import android.net.Uri; import org.emergent.android.weave.Constants; import org.emergent.android.weave.client.CollectionNode; import org.json.JSONException; /* * Copyright 2010 Patrick Woodworth * * 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 org.emergent.android.weave.persistence; /** * @author Patrick Woodworth */ public class Passwords { public static final String AUTHORITY = Constants.PASSWORD_PROVIDER_AUTHORITY; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); public static final Weaves.Updater UPDATER =
new Weaves.Updater(CONTENT_URI, CollectionNode.STORAGE_PASSWORDS) {
emergentdotorg/shaman
src/org/emergent/android/weave/WeaveListCursorAdapter.java
// Path: src/org/emergent/android/weave/persistence/Weaves.java // public class Weaves { // // public static void setBasicContentValues(ContentValues values, Record info) throws JSONException { // boolean isDeleted = info.isDeleted(); // putColumnValue(values, Columns.UUID, info.getId()); // putColumnValue(values, Columns.IS_DELETED, isDeleted); // putColumnValue(values, Columns.LAST_MODIFIED, info.getModifiedInSeconds()); // } // // public static void putColumnValue(ContentValues values, String colName, String value) { // values.put(colName, value); // } // // public static void putColumnValue(ContentValues values, String colName, long value) { // values.put(colName, value); // } // // public static void putColumnValue(ContentValues values, String colName, boolean value) { // values.put(colName, value); // } // // public static class Columns implements BaseColumns { // // // BaseColumn contains _id. // // public static final String UUID = "uuid"; // public static final String SORT_INDEX = "sortIndex"; // public static final String LAST_MODIFIED = "lastModified"; // public static final String IS_DELETED = "isDeleted"; // } // // public static abstract class Updater { // // private final Uri m_authority; // private final CollectionNode m_collectionNode; // // Updater(Uri authority, CollectionNode colNode) { // m_authority = authority; // m_collectionNode = colNode; // } // // public Uri getAuthority() { // return m_authority; // } // // public String getNodePath() { // return m_collectionNode.nodePath; // } // // public String getEngineName() { // return m_collectionNode.engineName; // } // // public int deleteRecords(ContentResolver cResolver) { // return cResolver.delete(m_authority, "", new String[] {} ); // } // // public void insertRecord(ContentResolver cResolver, Record info) throws JSONException { // ContentValues values = new ContentValues(); // setContentValues(values, info); // cResolver.insert(m_authority, values); // } // // public int insertRecords(ContentResolver cResolver, List<Record> infos) throws JSONException { // ContentValues[] valuesArray = new ContentValues[infos.size()]; // int ii = 0; // for (Record info : infos) { // ContentValues values = new ContentValues(); // setContentValues(values, info); // valuesArray[ii++] = values; // } // return cResolver.bulkInsert(m_authority, valuesArray); // } // // protected abstract void setContentValues(ContentValues values, Record info) throws JSONException; // } // // /** // * @author Patrick Woodworth // */ // public static class Record { // // private WeaveBasicObject m_wbo; // private JSONObject m_decryptedPayload; // // public Record(WeaveBasicObject wbo, JSONObject decryptedPayload) { // m_wbo = wbo; // m_decryptedPayload = decryptedPayload; // } // // public String getId() throws JSONException { // return getProperty("id"); // } // // // public boolean isDeleted() throws JSONException { // return m_decryptedPayload.has("deleted") && m_decryptedPayload.getBoolean("deleted"); // } // // public String getModified() throws JSONException { // return m_wbo.getModified(); // } // // public long getModifiedInSeconds() { // long mod = 0; // try { // double modDouble = Double.parseDouble(getModified()) * 1000; // mod = Math.round(modDouble) / 1000; // } catch (Exception ignored) { // } // return mod; // } // // public Date getModifiedDate() throws JSONException { // return toModifiedTimeDate(getModified()); // } // // public String getProperty(String key) throws JSONException { // if (m_decryptedPayload.has(key)) // return m_decryptedPayload.getString(key); // return null; // } // // /** // * Inline of <code>WeaveUtil.toModifiedTimeDate(String)</code> // * @todo stop inline // */ // private static Date toModifiedTimeDate(String modified) { // long now = System.currentTimeMillis(); // try { // double modDouble = Double.parseDouble(modified) * 1000; // long mod = Math.round(modDouble); // return new Date(mod); // } catch (Exception e) { // return new Date(); // todo buggy ? // } // } // } // }
import android.content.Context; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.emergent.android.weave.persistence.Weaves; import java.text.SimpleDateFormat; import java.util.Date;
* @see android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); TextView urlTextView = (TextView)v.findViewById(R.id.url); if (urlTextView != null) { String urlVal = urlTextView.getText().toString(); if (urlVal == null || urlVal.trim().length() < 1) { urlTextView.setVisibility(View.GONE); } else { urlTextView.setVisibility(View.VISIBLE); } } View star = v.findViewById(R.id.star); if (star != null) star.setVisibility(View.GONE); View favicon = v.findViewById(R.id.favicon); if (favicon != null) favicon.setVisibility(View.GONE); return v; } public static class MyViewBinder implements ViewBinder { private final SimpleDateFormat m_dateFormat = new SimpleDateFormat(); @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (view instanceof TextView &&
// Path: src/org/emergent/android/weave/persistence/Weaves.java // public class Weaves { // // public static void setBasicContentValues(ContentValues values, Record info) throws JSONException { // boolean isDeleted = info.isDeleted(); // putColumnValue(values, Columns.UUID, info.getId()); // putColumnValue(values, Columns.IS_DELETED, isDeleted); // putColumnValue(values, Columns.LAST_MODIFIED, info.getModifiedInSeconds()); // } // // public static void putColumnValue(ContentValues values, String colName, String value) { // values.put(colName, value); // } // // public static void putColumnValue(ContentValues values, String colName, long value) { // values.put(colName, value); // } // // public static void putColumnValue(ContentValues values, String colName, boolean value) { // values.put(colName, value); // } // // public static class Columns implements BaseColumns { // // // BaseColumn contains _id. // // public static final String UUID = "uuid"; // public static final String SORT_INDEX = "sortIndex"; // public static final String LAST_MODIFIED = "lastModified"; // public static final String IS_DELETED = "isDeleted"; // } // // public static abstract class Updater { // // private final Uri m_authority; // private final CollectionNode m_collectionNode; // // Updater(Uri authority, CollectionNode colNode) { // m_authority = authority; // m_collectionNode = colNode; // } // // public Uri getAuthority() { // return m_authority; // } // // public String getNodePath() { // return m_collectionNode.nodePath; // } // // public String getEngineName() { // return m_collectionNode.engineName; // } // // public int deleteRecords(ContentResolver cResolver) { // return cResolver.delete(m_authority, "", new String[] {} ); // } // // public void insertRecord(ContentResolver cResolver, Record info) throws JSONException { // ContentValues values = new ContentValues(); // setContentValues(values, info); // cResolver.insert(m_authority, values); // } // // public int insertRecords(ContentResolver cResolver, List<Record> infos) throws JSONException { // ContentValues[] valuesArray = new ContentValues[infos.size()]; // int ii = 0; // for (Record info : infos) { // ContentValues values = new ContentValues(); // setContentValues(values, info); // valuesArray[ii++] = values; // } // return cResolver.bulkInsert(m_authority, valuesArray); // } // // protected abstract void setContentValues(ContentValues values, Record info) throws JSONException; // } // // /** // * @author Patrick Woodworth // */ // public static class Record { // // private WeaveBasicObject m_wbo; // private JSONObject m_decryptedPayload; // // public Record(WeaveBasicObject wbo, JSONObject decryptedPayload) { // m_wbo = wbo; // m_decryptedPayload = decryptedPayload; // } // // public String getId() throws JSONException { // return getProperty("id"); // } // // // public boolean isDeleted() throws JSONException { // return m_decryptedPayload.has("deleted") && m_decryptedPayload.getBoolean("deleted"); // } // // public String getModified() throws JSONException { // return m_wbo.getModified(); // } // // public long getModifiedInSeconds() { // long mod = 0; // try { // double modDouble = Double.parseDouble(getModified()) * 1000; // mod = Math.round(modDouble) / 1000; // } catch (Exception ignored) { // } // return mod; // } // // public Date getModifiedDate() throws JSONException { // return toModifiedTimeDate(getModified()); // } // // public String getProperty(String key) throws JSONException { // if (m_decryptedPayload.has(key)) // return m_decryptedPayload.getString(key); // return null; // } // // /** // * Inline of <code>WeaveUtil.toModifiedTimeDate(String)</code> // * @todo stop inline // */ // private static Date toModifiedTimeDate(String modified) { // long now = System.currentTimeMillis(); // try { // double modDouble = Double.parseDouble(modified) * 1000; // long mod = Math.round(modDouble); // return new Date(mod); // } catch (Exception e) { // return new Date(); // todo buggy ? // } // } // } // } // Path: src/org/emergent/android/weave/WeaveListCursorAdapter.java import android.content.Context; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.emergent.android.weave.persistence.Weaves; import java.text.SimpleDateFormat; import java.util.Date; * @see android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); TextView urlTextView = (TextView)v.findViewById(R.id.url); if (urlTextView != null) { String urlVal = urlTextView.getText().toString(); if (urlVal == null || urlVal.trim().length() < 1) { urlTextView.setVisibility(View.GONE); } else { urlTextView.setVisibility(View.VISIBLE); } } View star = v.findViewById(R.id.star); if (star != null) star.setVisibility(View.GONE); View favicon = v.findViewById(R.id.favicon); if (favicon != null) favicon.setVisibility(View.GONE); return v; } public static class MyViewBinder implements ViewBinder { private final SimpleDateFormat m_dateFormat = new SimpleDateFormat(); @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (view instanceof TextView &&
Weaves.Columns.LAST_MODIFIED.equals(cursor.getColumnName(columnIndex))) {
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/instructions/InstructionClass4.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // }
import org.z64sim.program.Instruction; import org.z64sim.memory.Memory;
break; case "std": this.type = 0x0c; this.val = 1; break; case "sto": //GHALI this.type = 0x0d; this.val = 1; break; default: throw new RuntimeException("Unknown Class 4 instruction: " + mnemonic); } enc[0] = (byte)(enc[0] | this.type); this.setEncoding(enc); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // } // Path: simulator/src/org/z64sim/program/instructions/InstructionClass4.java import org.z64sim.program.Instruction; import org.z64sim.memory.Memory; break; case "std": this.type = 0x0c; this.val = 1; break; case "sto": //GHALI this.type = 0x0d; this.val = 1; break; default: throw new RuntimeException("Unknown Class 4 instruction: " + mnemonic); } enc[0] = (byte)(enc[0] | this.type); this.setEncoding(enc); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
b[i] = Memory.getProgram().program[address + i];
alessandropellegrini/z64sim
simulator/src/org/z64sim/memory/window/MemoryTopComponent.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // }
import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.z64sim.memory.window; /** * Top component which displays something. */ @ConvertAsProperties( dtd = "-//org.z64sim.memory//Memory//EN", autostore = false ) @TopComponent.Description( preferredID = "MemoryTopComponent", iconBase = "org/z64sim/memory/window/memory.png", persistenceType = TopComponent.PERSISTENCE_ONLY_OPENED ) @TopComponent.Registration(mode = "properties", openAtStartup = true) @ActionID(category = "Window", id = "org.z64sim.memory.MemoryTopComponent") @ActionReference(path = "Menu/Window", position = 3) @TopComponent.OpenActionRegistration( displayName = "#CTL_MemoryAction", preferredID = "MemoryTopComponent" ) @Messages({ "CTL_MemoryAction=Memory", "CTL_MemoryTopComponent=Memory View", "HINT_MemoryTopComponent=This window allows to explore/modify memory content" }) public final class MemoryTopComponent extends TopComponent { public MemoryTopComponent() { initComponents(); setName(Bundle.CTL_MemoryTopComponent()); setToolTipText(Bundle.HINT_MemoryTopComponent());
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // Path: simulator/src/org/z64sim/memory/window/MemoryTopComponent.java import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.z64sim.memory.window; /** * Top component which displays something. */ @ConvertAsProperties( dtd = "-//org.z64sim.memory//Memory//EN", autostore = false ) @TopComponent.Description( preferredID = "MemoryTopComponent", iconBase = "org/z64sim/memory/window/memory.png", persistenceType = TopComponent.PERSISTENCE_ONLY_OPENED ) @TopComponent.Registration(mode = "properties", openAtStartup = true) @ActionID(category = "Window", id = "org.z64sim.memory.MemoryTopComponent") @ActionReference(path = "Menu/Window", position = 3) @TopComponent.OpenActionRegistration( displayName = "#CTL_MemoryAction", preferredID = "MemoryTopComponent" ) @Messages({ "CTL_MemoryAction=Memory", "CTL_MemoryTopComponent=Memory View", "HINT_MemoryTopComponent=This window allows to explore/modify memory content" }) public final class MemoryTopComponent extends TopComponent { public MemoryTopComponent() { initComponents(); setName(Bundle.CTL_MemoryTopComponent()); setToolTipText(Bundle.HINT_MemoryTopComponent());
Memory.setWindow(this);
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/Program.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // }
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory;
Byte[] text = this.text.toArray(new Byte[this.text.size()]); Byte[] data = this.data.toArray(new Byte[this.data.size()]); System.arraycopy(text, 0, this.program, 0, TextS); System.arraycopy(this.IDT, 0, this.program, 0, this.IDT.length); System.arraycopy(data, 0, this.program, TextS, DataS); this._dataStart = TextS; for(int i = 0; i < Program.STACK_SIZE; i++) { this.program[TextS + DataS + i] = 0; } // This Program does not need anymore intermediate assemblying // information, so we remove references. This is particularly useful // when this object is serialized to save an executable. this.labels.clear(); this.labels = null; this.equs.clear(); this.equs = null; this.relocations.clear(); this.relocations = null; this.IDT = null; this.text.clear(); this.text = null; this.data.clear(); this.data = null; // Register this as the currently assembled program
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // } // Path: simulator/src/org/z64sim/program/Program.java import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory; Byte[] text = this.text.toArray(new Byte[this.text.size()]); Byte[] data = this.data.toArray(new Byte[this.data.size()]); System.arraycopy(text, 0, this.program, 0, TextS); System.arraycopy(this.IDT, 0, this.program, 0, this.IDT.length); System.arraycopy(data, 0, this.program, TextS, DataS); this._dataStart = TextS; for(int i = 0; i < Program.STACK_SIZE; i++) { this.program[TextS + DataS + i] = 0; } // This Program does not need anymore intermediate assemblying // information, so we remove references. This is particularly useful // when this object is serialized to save an executable. this.labels.clear(); this.labels = null; this.equs.clear(); this.equs = null; this.relocations.clear(); this.relocations = null; this.IDT = null; this.text.clear(); this.text = null; this.data.clear(); this.data = null; // Register this as the currently assembled program
Memory.setProgram(this);
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/Program.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // }
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory;
this.data.add((byte)(val >> 16)); this.data.add((byte)(val >> 8)); this.data.add((byte)val); return addr; } public long addData(byte[] val) { long addr = this.data.size(); // Fill memory in between for(int i = 0; i < val.length; i++) { this.data.add(val[i]); } return addr; } /** * A relocation entry. Points to the initial address of the instruction. It * is then the role of the relocate() method to account for differences in * the various instruction formats. */ private class RelocationEntry { private final long applyTo; private final String label; public RelocationEntry(long applyTo, String label) { this.applyTo = applyTo; this.label = label; }
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // } // Path: simulator/src/org/z64sim/program/Program.java import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory; this.data.add((byte)(val >> 16)); this.data.add((byte)(val >> 8)); this.data.add((byte)val); return addr; } public long addData(byte[] val) { long addr = this.data.size(); // Fill memory in between for(int i = 0; i < val.length; i++) { this.data.add(val[i]); } return addr; } /** * A relocation entry. Points to the initial address of the instruction. It * is then the role of the relocate() method to account for differences in * the various instruction formats. */ private class RelocationEntry { private final long applyTo; private final String label; public RelocationEntry(long applyTo, String label) { this.applyTo = applyTo; this.label = label; }
private void relocateImmediate(OperandImmediate op, Instruction insn) throws ProgramException {