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
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/transformation/SimpleTransformation.java
// Path: webimageloader/src/main/java/com/webimageloader/util/BitmapUtils.java // public class BitmapUtils { // public static Bitmap.CompressFormat getCompressFormat(String contentType) { // if ("image/png".equals(contentType)) { // return Bitmap.CompressFormat.PNG; // } else if ("image/jpeg".equals(contentType)) { // return Bitmap.CompressFormat.JPEG; // } else { // // Unknown format, use default // return Constants.DEFAULT_COMPRESS_FORMAT; // } // } // // @TargetApi(14) // public static String getContentType(Bitmap.CompressFormat format) { // switch (format) { // case PNG: // return "image/png"; // case JPEG: // return "image/jpeg"; // case WEBP: // return "image/webp"; // default: // // Unknown format, use default // return getContentType(Constants.DEFAULT_COMPRESS_FORMAT); // } // } // // public static Bitmap decodeStream(InputStream is) throws IOException { // Bitmap b = BitmapFactory.decodeStream(is); // if (b == null) { // throw new IOException("Failed to create bitmap, decodeStream() returned null"); // } // // return b; // } // // private BitmapUtils() {} // } // // Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // }
import java.io.IOException; import java.io.InputStream; import com.webimageloader.util.BitmapUtils; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat;
package com.webimageloader.transformation; /** * Adapter class to use if you don't need the {@link InputStream} provided by * the base {@link Transformation} class. * * @author Alexander Blom <alexanderblom.se> */ public abstract class SimpleTransformation implements Transformation { /** * {@inheritDoc} * * @return null, meaning use default format */ @Override public CompressFormat getCompressFormat() { return null; } /** * {@inheritDoc} */ @Override public Bitmap transform(InputSupplier input) throws IOException { InputStream is = input.getInput(); try {
// Path: webimageloader/src/main/java/com/webimageloader/util/BitmapUtils.java // public class BitmapUtils { // public static Bitmap.CompressFormat getCompressFormat(String contentType) { // if ("image/png".equals(contentType)) { // return Bitmap.CompressFormat.PNG; // } else if ("image/jpeg".equals(contentType)) { // return Bitmap.CompressFormat.JPEG; // } else { // // Unknown format, use default // return Constants.DEFAULT_COMPRESS_FORMAT; // } // } // // @TargetApi(14) // public static String getContentType(Bitmap.CompressFormat format) { // switch (format) { // case PNG: // return "image/png"; // case JPEG: // return "image/jpeg"; // case WEBP: // return "image/webp"; // default: // // Unknown format, use default // return getContentType(Constants.DEFAULT_COMPRESS_FORMAT); // } // } // // public static Bitmap decodeStream(InputStream is) throws IOException { // Bitmap b = BitmapFactory.decodeStream(is); // if (b == null) { // throw new IOException("Failed to create bitmap, decodeStream() returned null"); // } // // return b; // } // // private BitmapUtils() {} // } // // Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // } // Path: webimageloader/src/main/java/com/webimageloader/transformation/SimpleTransformation.java import java.io.IOException; import java.io.InputStream; import com.webimageloader.util.BitmapUtils; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; package com.webimageloader.transformation; /** * Adapter class to use if you don't need the {@link InputStream} provided by * the base {@link Transformation} class. * * @author Alexander Blom <alexanderblom.se> */ public abstract class SimpleTransformation implements Transformation { /** * {@inheritDoc} * * @return null, meaning use default format */ @Override public CompressFormat getCompressFormat() { return null; } /** * {@inheritDoc} */ @Override public Bitmap transform(InputSupplier input) throws IOException { InputStream is = input.getInput(); try {
Bitmap b = BitmapUtils.decodeStream(is);
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/util/ListenerFuture.java
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderWork.java // public class LoaderWork { // private final Loader.Listener listener; // private final ImageLoader.ProgressListener progressListener; // private final List<Future<?>> futures; // // private volatile boolean cancelled = false; // // public LoaderWork(Loader.Listener listener, ImageLoader.ProgressListener progressListener) { // this.listener = listener; // this.progressListener = progressListener; // this.futures = new ArrayList<Future<?>>(); // } // // public void cancel() { // cancelled = true; // // synchronized (futures) { // for (Future<?> future : futures) { // future.cancel(false); // } // } // } // // public void start(List<Loader> loaderChain, LoaderRequest request) { // Iterator<Loader> it = loaderChain.iterator(); // Loader loader = it.next(); // // loader.load(new Manager(it, listener), request); // } // // public class Manager { // private Iterator<Loader> chain; // private Loader.Listener listener; // // private Loader nextLoader; // // Manager(Iterator<Loader> chain, Loader.Listener listener) { // this.chain = chain; // this.listener = listener; // // if (chain.hasNext()) { // nextLoader = chain.next(); // } // } // // public boolean isCancelled() { // return cancelled; // } // // public void addFuture(Future<?> future) { // synchronized (futures) { // futures.add(future); // } // } // // public void next(LoaderRequest request) { // // Load using old listener // next(request, listener); // } // // public void next(LoaderRequest request, Loader.Listener listener) { // if (!cancelled) { // Manager nextManager = new Manager(chain, listener); // nextLoader.load(nextManager, request); // } // } // // public void publishProgress(float value) { // if (!cancelled) { // progressListener.onProgress(value); // } // } // // public void deliverStream(InputSupplier is, Metadata metadata) { // if (!cancelled) { // listener.onStreamLoaded(is, metadata); // } // } // // public void deliverBitmap(Bitmap b, Metadata metadata) { // if (!cancelled) { // listener.onBitmapLoaded(b, metadata); // } // } // // public void deliverError(Throwable t) { // if (!cancelled) { // listener.onError(t); // } // } // // public void deliverNotMotified(Metadata metadata) { // if (!cancelled) { // listener.onNotModified(metadata); // } // } // } // }
import com.webimageloader.loader.LoaderWork;
package com.webimageloader.util; public class ListenerFuture implements Runnable { public interface Task { void run() throws Exception; } private Task task;
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderWork.java // public class LoaderWork { // private final Loader.Listener listener; // private final ImageLoader.ProgressListener progressListener; // private final List<Future<?>> futures; // // private volatile boolean cancelled = false; // // public LoaderWork(Loader.Listener listener, ImageLoader.ProgressListener progressListener) { // this.listener = listener; // this.progressListener = progressListener; // this.futures = new ArrayList<Future<?>>(); // } // // public void cancel() { // cancelled = true; // // synchronized (futures) { // for (Future<?> future : futures) { // future.cancel(false); // } // } // } // // public void start(List<Loader> loaderChain, LoaderRequest request) { // Iterator<Loader> it = loaderChain.iterator(); // Loader loader = it.next(); // // loader.load(new Manager(it, listener), request); // } // // public class Manager { // private Iterator<Loader> chain; // private Loader.Listener listener; // // private Loader nextLoader; // // Manager(Iterator<Loader> chain, Loader.Listener listener) { // this.chain = chain; // this.listener = listener; // // if (chain.hasNext()) { // nextLoader = chain.next(); // } // } // // public boolean isCancelled() { // return cancelled; // } // // public void addFuture(Future<?> future) { // synchronized (futures) { // futures.add(future); // } // } // // public void next(LoaderRequest request) { // // Load using old listener // next(request, listener); // } // // public void next(LoaderRequest request, Loader.Listener listener) { // if (!cancelled) { // Manager nextManager = new Manager(chain, listener); // nextLoader.load(nextManager, request); // } // } // // public void publishProgress(float value) { // if (!cancelled) { // progressListener.onProgress(value); // } // } // // public void deliverStream(InputSupplier is, Metadata metadata) { // if (!cancelled) { // listener.onStreamLoaded(is, metadata); // } // } // // public void deliverBitmap(Bitmap b, Metadata metadata) { // if (!cancelled) { // listener.onBitmapLoaded(b, metadata); // } // } // // public void deliverError(Throwable t) { // if (!cancelled) { // listener.onError(t); // } // } // // public void deliverNotMotified(Metadata metadata) { // if (!cancelled) { // listener.onNotModified(metadata); // } // } // } // } // Path: webimageloader/src/main/java/com/webimageloader/util/ListenerFuture.java import com.webimageloader.loader.LoaderWork; package com.webimageloader.util; public class ListenerFuture implements Runnable { public interface Task { void run() throws Exception; } private Task task;
private LoaderWork.Manager manager;
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java
// Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // }
import java.io.IOException; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap;
package com.webimageloader.transformation; /** * Transformation to apply to an image while loading it * @author Alexander Blom <alexanderblom.se> */ public interface Transformation { /** * Get the identified for this transformation. It should be unique and include any * Parameters passed to this transformation. * * @return the identifier */ String getIdentifier(); /** * Get the format used when saving the result of this transformation. This * can be useful for example when relying on alpha. * * @return the bitmap compress format, null for default */ Bitmap.CompressFormat getCompressFormat(); /** * Transform this {@link InputSupplier} to a {@link Bitmap}. * * @param input original {@link InputSupplier} * @return transformed {@link Bitmap} * @throws IOException if the conversion failed */
// Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // } // Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java import java.io.IOException; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap; package com.webimageloader.transformation; /** * Transformation to apply to an image while loading it * @author Alexander Blom <alexanderblom.se> */ public interface Transformation { /** * Get the identified for this transformation. It should be unique and include any * Parameters passed to this transformation. * * @return the identifier */ String getIdentifier(); /** * Get the format used when saving the result of this transformation. This * can be useful for example when relying on alpha. * * @return the bitmap compress format, null for default */ Bitmap.CompressFormat getCompressFormat(); /** * Transform this {@link InputSupplier} to a {@link Bitmap}. * * @param input original {@link InputSupplier} * @return transformed {@link Bitmap} * @throws IOException if the conversion failed */
Bitmap transform(InputSupplier input) throws IOException;
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/loader/LoaderManager.java
// Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.webimageloader.transformation.Transformation; import android.graphics.Bitmap;
// over in multiple threads standardChain = Collections.unmodifiableList(standardChain); transformationChain = Collections.unmodifiableList(transformationChain); pendingRequests = new PendingRequests(memoryCache); } public MemoryCache getMemoryCache() { return memoryCache; } public Bitmap load(Object tag, LoaderRequest request, Listener listener) { Bitmap b = pendingRequests.getBitmap(tag, request); if (b != null) { return b; } // Send an empty listener instead of null if (listener == null) { listener = EMPTY_LISTENER; } LoaderWork work = pendingRequests.addRequest(tag, request, listener); // A request is already pending, don't load anything if (work == null) { return null; } // Use different chains depending if we have a transformation or not
// Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // } // Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderManager.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.webimageloader.transformation.Transformation; import android.graphics.Bitmap; // over in multiple threads standardChain = Collections.unmodifiableList(standardChain); transformationChain = Collections.unmodifiableList(transformationChain); pendingRequests = new PendingRequests(memoryCache); } public MemoryCache getMemoryCache() { return memoryCache; } public Bitmap load(Object tag, LoaderRequest request, Listener listener) { Bitmap b = pendingRequests.getBitmap(tag, request); if (b != null) { return b; } // Send an empty listener instead of null if (listener == null) { listener = EMPTY_LISTENER; } LoaderWork work = pendingRequests.addRequest(tag, request, listener); // A request is already pending, don't load anything if (work == null) { return null; } // Use different chains depending if we have a transformation or not
Transformation t = request.getTransformation();
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/Request.java
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderRequest.java // public class LoaderRequest { // private String url; // private Transformation transformation; // private Metadata metadata; // private EnumSet<Request.Flag> flags; // // private String cacheKey; // // public LoaderRequest(String url, Transformation transformation, EnumSet<Request.Flag> flags) { // if (url == null) { // throw new IllegalArgumentException("url may not be null"); // } // // this.url = url; // this.transformation = transformation; // this.flags = flags; // // if (transformation != null) { // cacheKey = url + transformation.getIdentifier(); // } else { // cacheKey = url; // } // } // // public LoaderRequest withoutTransformation() { // return new LoaderRequest(url, null, flags); // } // // public LoaderRequest withMetadata(Metadata metadata) { // LoaderRequest r = new LoaderRequest(url, transformation, flags); // r.metadata = metadata; // // return r; // } // // public String getUrl() { // return url; // } // // public Transformation getTransformation() { // return transformation; // } // // public Metadata getMetadata() { // return metadata; // } // // public String getCacheKey() { // return cacheKey; // } // // public boolean hasFlag(Request.Flag flag) { // return flags.contains(flag); // } // // @Override // public int hashCode() { // return cacheKey.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj instanceof LoaderRequest) { // LoaderRequest request = (LoaderRequest) obj; // return cacheKey.equals(request.getCacheKey()); // } else { // return false; // } // } // // @Override // public String toString() { // String f = flags.isEmpty() ? "" : ", flags=" + flags; // // if (transformation != null) { // return url + f + " with transformation " + '"' + transformation.getIdentifier() + '"'; // } else { // return url + f; // } // } // } // // Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // }
import java.io.File; import java.util.EnumSet; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import com.webimageloader.loader.LoaderRequest; import com.webimageloader.transformation.Transformation;
package com.webimageloader; /** * Class describing a specific request including transformations to be applied. * * @author Alexander Blom <alexanderblom.se> */ public class Request { public enum Flag { /** * Flag which makes the request ignore any possibly cached bitmaps */ IGNORE_CACHE, /** * Flag which makes the request don't save its result to cache */ NO_CACHE, /** * Flag for skipping the disk cache, both for retrieval and storing, * useful for images already fetched from disk. */ SKIP_DISK_CACHE } private String url;
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderRequest.java // public class LoaderRequest { // private String url; // private Transformation transformation; // private Metadata metadata; // private EnumSet<Request.Flag> flags; // // private String cacheKey; // // public LoaderRequest(String url, Transformation transformation, EnumSet<Request.Flag> flags) { // if (url == null) { // throw new IllegalArgumentException("url may not be null"); // } // // this.url = url; // this.transformation = transformation; // this.flags = flags; // // if (transformation != null) { // cacheKey = url + transformation.getIdentifier(); // } else { // cacheKey = url; // } // } // // public LoaderRequest withoutTransformation() { // return new LoaderRequest(url, null, flags); // } // // public LoaderRequest withMetadata(Metadata metadata) { // LoaderRequest r = new LoaderRequest(url, transformation, flags); // r.metadata = metadata; // // return r; // } // // public String getUrl() { // return url; // } // // public Transformation getTransformation() { // return transformation; // } // // public Metadata getMetadata() { // return metadata; // } // // public String getCacheKey() { // return cacheKey; // } // // public boolean hasFlag(Request.Flag flag) { // return flags.contains(flag); // } // // @Override // public int hashCode() { // return cacheKey.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj instanceof LoaderRequest) { // LoaderRequest request = (LoaderRequest) obj; // return cacheKey.equals(request.getCacheKey()); // } else { // return false; // } // } // // @Override // public String toString() { // String f = flags.isEmpty() ? "" : ", flags=" + flags; // // if (transformation != null) { // return url + f + " with transformation " + '"' + transformation.getIdentifier() + '"'; // } else { // return url + f; // } // } // } // // Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // } // Path: webimageloader/src/main/java/com/webimageloader/Request.java import java.io.File; import java.util.EnumSet; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import com.webimageloader.loader.LoaderRequest; import com.webimageloader.transformation.Transformation; package com.webimageloader; /** * Class describing a specific request including transformations to be applied. * * @author Alexander Blom <alexanderblom.se> */ public class Request { public enum Flag { /** * Flag which makes the request ignore any possibly cached bitmaps */ IGNORE_CACHE, /** * Flag which makes the request don't save its result to cache */ NO_CACHE, /** * Flag for skipping the disk cache, both for retrieval and storing, * useful for images already fetched from disk. */ SKIP_DISK_CACHE } private String url;
private Transformation transformation;
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/Request.java
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderRequest.java // public class LoaderRequest { // private String url; // private Transformation transformation; // private Metadata metadata; // private EnumSet<Request.Flag> flags; // // private String cacheKey; // // public LoaderRequest(String url, Transformation transformation, EnumSet<Request.Flag> flags) { // if (url == null) { // throw new IllegalArgumentException("url may not be null"); // } // // this.url = url; // this.transformation = transformation; // this.flags = flags; // // if (transformation != null) { // cacheKey = url + transformation.getIdentifier(); // } else { // cacheKey = url; // } // } // // public LoaderRequest withoutTransformation() { // return new LoaderRequest(url, null, flags); // } // // public LoaderRequest withMetadata(Metadata metadata) { // LoaderRequest r = new LoaderRequest(url, transformation, flags); // r.metadata = metadata; // // return r; // } // // public String getUrl() { // return url; // } // // public Transformation getTransformation() { // return transformation; // } // // public Metadata getMetadata() { // return metadata; // } // // public String getCacheKey() { // return cacheKey; // } // // public boolean hasFlag(Request.Flag flag) { // return flags.contains(flag); // } // // @Override // public int hashCode() { // return cacheKey.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj instanceof LoaderRequest) { // LoaderRequest request = (LoaderRequest) obj; // return cacheKey.equals(request.getCacheKey()); // } else { // return false; // } // } // // @Override // public String toString() { // String f = flags.isEmpty() ? "" : ", flags=" + flags; // // if (transformation != null) { // return url + f + " with transformation " + '"' + transformation.getIdentifier() + '"'; // } else { // return url + f; // } // } // } // // Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // }
import java.io.File; import java.util.EnumSet; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import com.webimageloader.loader.LoaderRequest; import com.webimageloader.transformation.Transformation;
public Request setTransformation(Transformation transformation) { this.transformation = transformation; return this; } /** * Add a flag to this request * * @param flag the flag to be added * @return this request */ public Request addFlag(Flag flag) { flags.add(flag); return this; } /** * Add multiple flags to this request * * @param flags the flags to be added * @return this request */ public Request addFlags(EnumSet<Flag> flags) { this.flags.addAll(flags); return this; }
// Path: webimageloader/src/main/java/com/webimageloader/loader/LoaderRequest.java // public class LoaderRequest { // private String url; // private Transformation transformation; // private Metadata metadata; // private EnumSet<Request.Flag> flags; // // private String cacheKey; // // public LoaderRequest(String url, Transformation transformation, EnumSet<Request.Flag> flags) { // if (url == null) { // throw new IllegalArgumentException("url may not be null"); // } // // this.url = url; // this.transformation = transformation; // this.flags = flags; // // if (transformation != null) { // cacheKey = url + transformation.getIdentifier(); // } else { // cacheKey = url; // } // } // // public LoaderRequest withoutTransformation() { // return new LoaderRequest(url, null, flags); // } // // public LoaderRequest withMetadata(Metadata metadata) { // LoaderRequest r = new LoaderRequest(url, transformation, flags); // r.metadata = metadata; // // return r; // } // // public String getUrl() { // return url; // } // // public Transformation getTransformation() { // return transformation; // } // // public Metadata getMetadata() { // return metadata; // } // // public String getCacheKey() { // return cacheKey; // } // // public boolean hasFlag(Request.Flag flag) { // return flags.contains(flag); // } // // @Override // public int hashCode() { // return cacheKey.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj instanceof LoaderRequest) { // LoaderRequest request = (LoaderRequest) obj; // return cacheKey.equals(request.getCacheKey()); // } else { // return false; // } // } // // @Override // public String toString() { // String f = flags.isEmpty() ? "" : ", flags=" + flags; // // if (transformation != null) { // return url + f + " with transformation " + '"' + transformation.getIdentifier() + '"'; // } else { // return url + f; // } // } // } // // Path: webimageloader/src/main/java/com/webimageloader/transformation/Transformation.java // public interface Transformation { // /** // * Get the identified for this transformation. It should be unique and include any // * Parameters passed to this transformation. // * // * @return the identifier // */ // String getIdentifier(); // // /** // * Get the format used when saving the result of this transformation. This // * can be useful for example when relying on alpha. // * // * @return the bitmap compress format, null for default // */ // Bitmap.CompressFormat getCompressFormat(); // // /** // * Transform this {@link InputSupplier} to a {@link Bitmap}. // * // * @param input original {@link InputSupplier} // * @return transformed {@link Bitmap} // * @throws IOException if the conversion failed // */ // Bitmap transform(InputSupplier input) throws IOException; // // /** // * Transform this {@link Bitmap} to a new {@link Bitmap}. // * // * @param b original {@link Bitmap} // * @return transformed {@link Bitmap} // */ // Bitmap transform(Bitmap b); // } // Path: webimageloader/src/main/java/com/webimageloader/Request.java import java.io.File; import java.util.EnumSet; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import com.webimageloader.loader.LoaderRequest; import com.webimageloader.transformation.Transformation; public Request setTransformation(Transformation transformation) { this.transformation = transformation; return this; } /** * Add a flag to this request * * @param flag the flag to be added * @return this request */ public Request addFlag(Flag flag) { flags.add(flag); return this; } /** * Add multiple flags to this request * * @param flags the flags to be added * @return this request */ public Request addFlags(EnumSet<Flag> flags) { this.flags.addAll(flags); return this; }
LoaderRequest toLoaderRequest() {
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/loader/Loader.java
// Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // }
import java.util.Iterator; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap;
package com.webimageloader.loader; public interface Loader { interface Listener {
// Path: webimageloader/src/main/java/com/webimageloader/util/InputSupplier.java // public interface InputSupplier { // /** // * Get the length of the supplied {@link InputStream} // * // * @return the length // * @throws IOException if opening the stream or file failed // */ // long getLength() throws IOException; // // /** // * Open a new {@link InputStream}, you should be sure to close any previously // * opened streams before // * // * @return a fresh stream which you are responsible for closing // * @throws IOException if opening the stream failed // */ // InputStream getInput() throws IOException; // } // Path: webimageloader/src/main/java/com/webimageloader/loader/Loader.java import java.util.Iterator; import com.webimageloader.util.InputSupplier; import android.graphics.Bitmap; package com.webimageloader.loader; public interface Loader { interface Listener {
void onStreamLoaded(InputSupplier input, Metadata metadata);
lexs/webimageloader
webimageloader/src/main/java/com/webimageloader/util/BitmapUtils.java
// Path: webimageloader/src/main/java/com/webimageloader/Constants.java // public class Constants { // public static final int DEFAULT_CONNECTION_TIMEOUT = 10 * 1000; // 10 sec // public static final int DEFAULT_READ_TIMEOUT = 15 * 1000; // 15 sec // public static final long DEFAULT_MAX_AGE = 3 * 24 * 60 * 60 * 1000; // Three days // public static final long MAX_AGE_INFINITY = 0; // public static final long MAX_AGE_NOT_FORCED = -1; // // public static final int DEFAULT_DISK_THREADS = 1; // public static final int DEFAULT_NETWORK_THREADS = 2; // // public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG; // public static final int DEFAULT_COMPRESS_QUALITY = 75; // // private Constants() {} // }
import java.io.IOException; import java.io.InputStream; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.webimageloader.Constants;
package com.webimageloader.util; public class BitmapUtils { public static Bitmap.CompressFormat getCompressFormat(String contentType) { if ("image/png".equals(contentType)) { return Bitmap.CompressFormat.PNG; } else if ("image/jpeg".equals(contentType)) { return Bitmap.CompressFormat.JPEG; } else { // Unknown format, use default
// Path: webimageloader/src/main/java/com/webimageloader/Constants.java // public class Constants { // public static final int DEFAULT_CONNECTION_TIMEOUT = 10 * 1000; // 10 sec // public static final int DEFAULT_READ_TIMEOUT = 15 * 1000; // 15 sec // public static final long DEFAULT_MAX_AGE = 3 * 24 * 60 * 60 * 1000; // Three days // public static final long MAX_AGE_INFINITY = 0; // public static final long MAX_AGE_NOT_FORCED = -1; // // public static final int DEFAULT_DISK_THREADS = 1; // public static final int DEFAULT_NETWORK_THREADS = 2; // // public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG; // public static final int DEFAULT_COMPRESS_QUALITY = 75; // // private Constants() {} // } // Path: webimageloader/src/main/java/com/webimageloader/util/BitmapUtils.java import java.io.IOException; import java.io.InputStream; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.webimageloader.Constants; package com.webimageloader.util; public class BitmapUtils { public static Bitmap.CompressFormat getCompressFormat(String contentType) { if ("image/png".equals(contentType)) { return Bitmap.CompressFormat.PNG; } else if ("image/jpeg".equals(contentType)) { return Bitmap.CompressFormat.JPEG; } else { // Unknown format, use default
return Constants.DEFAULT_COMPRESS_FORMAT;
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/utils/HandleSmsIntentService.java
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // }
import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.util.Log; import com.xiaomi.alertsystem.data.Constants;
package com.xiaomi.alertsystem.utils; public class HandleSmsIntentService extends Service { public static final String TAG = "HandleSmsIntentService"; public static final String StringKey = "sms"; private SmsBroadcastReceiver mSmsBroadcastReceiver; private IntentFilter mIntentFilter; @Override public void onCreate() { Log.d(TAG, "service created"); super.onCreate(); mSmsBroadcastReceiver = new SmsBroadcastReceiver(); mIntentFilter = new IntentFilter();
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // } // Path: src/com/xiaomi/alertsystem/utils/HandleSmsIntentService.java import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.util.Log; import com.xiaomi.alertsystem.data.Constants; package com.xiaomi.alertsystem.utils; public class HandleSmsIntentService extends Service { public static final String TAG = "HandleSmsIntentService"; public static final String StringKey = "sms"; private SmsBroadcastReceiver mSmsBroadcastReceiver; private IntentFilter mIntentFilter; @Override public void onCreate() { Log.d(TAG, "service created"); super.onCreate(); mSmsBroadcastReceiver = new SmsBroadcastReceiver(); mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Constants.SMS_RECEIVED);
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/ui/AlertThreadAdapter.java
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // }
import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta;
/** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; public class AlertThreadAdapter extends BaseAdapter { private static final String TAG = "AlertThreadAdapter";
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // } // Path: src/com/xiaomi/alertsystem/ui/AlertThreadAdapter.java import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta; /** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; public class AlertThreadAdapter extends BaseAdapter { private static final String TAG = "AlertThreadAdapter";
private List<AlertMeta> mSms = null;
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/ui/SmsNotifyAdapter.java
// Path: src/com/xiaomi/alertsystem/data/NotifyMeta.java // public class NotifyMeta { // // private String key; // private String mPerfKey; // private Context mContext; // // // public NotifyMeta(String key, Context context) { // super(); // this.key = key.toLowerCase(); // this.mContext = context; // // 为了兼容老版本 // this.mPerfKey = "pref_"+ key.toLowerCase() +"_notification "; // } // // public String getKey() { // return key; // } // // public String getName_cn() { // return key.toUpperCase() + "提醒设置"; // } // // public String getName_en() { // // 为了兼容老版本 // return mPerfKey; // } // // public int getValue() { // return CommonUtils.getSettingInt(mContext, mPerfKey, Constants.NOTIFICATION_VIBRATE); // } // // public String getTextValue() { // int index = getValue(); // return Constants.NOTIFICATION[index]; // } // public void setValue(int value) { // CommonUtils.setSettingInt(mContext, mPerfKey, value); // } // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.NotifyMeta; import java.util.List;
/** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; //TODO:deprecated, will not be used public class SmsNotifyAdapter extends BaseAdapter { private Context mContext;
// Path: src/com/xiaomi/alertsystem/data/NotifyMeta.java // public class NotifyMeta { // // private String key; // private String mPerfKey; // private Context mContext; // // // public NotifyMeta(String key, Context context) { // super(); // this.key = key.toLowerCase(); // this.mContext = context; // // 为了兼容老版本 // this.mPerfKey = "pref_"+ key.toLowerCase() +"_notification "; // } // // public String getKey() { // return key; // } // // public String getName_cn() { // return key.toUpperCase() + "提醒设置"; // } // // public String getName_en() { // // 为了兼容老版本 // return mPerfKey; // } // // public int getValue() { // return CommonUtils.getSettingInt(mContext, mPerfKey, Constants.NOTIFICATION_VIBRATE); // } // // public String getTextValue() { // int index = getValue(); // return Constants.NOTIFICATION[index]; // } // public void setValue(int value) { // CommonUtils.setSettingInt(mContext, mPerfKey, value); // } // // } // Path: src/com/xiaomi/alertsystem/ui/SmsNotifyAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.NotifyMeta; import java.util.List; /** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; //TODO:deprecated, will not be used public class SmsNotifyAdapter extends BaseAdapter { private Context mContext;
private List<NotifyMeta> mList;
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/utils/ThreadUpdateApp.java
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // }
import java.io.File; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Handler; import com.xiaomi.alertsystem.data.Constants;
package com.xiaomi.alertsystem.utils; public class ThreadUpdateApp extends Thread { private String mUrl; private Context mContext; private Handler mHandler; public ThreadUpdateApp(Context context, Handler handler) { mContext = context; mHandler = handler; } public void run() { PackageInfo pInfo = null; try { pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0); } catch (NameNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String version = pInfo.versionName;
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // } // Path: src/com/xiaomi/alertsystem/utils/ThreadUpdateApp.java import java.io.File; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Handler; import com.xiaomi.alertsystem.data.Constants; package com.xiaomi.alertsystem.utils; public class ThreadUpdateApp extends Thread { private String mUrl; private Context mContext; private Handler mHandler; public ThreadUpdateApp(Context context, Handler handler) { mContext = context; mHandler = handler; } public void run() { PackageInfo pInfo = null; try { pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0); } catch (NameNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String version = pInfo.versionName;
String ret = CommonUtils.execUrl(Constants.URL_UPDATE + version);
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/utils/ReadLocalSmsHelper.java
// Path: src/com/xiaomi/alertsystem/data/Sms.java // public class Sms implements Parcelable { // public long mId; // // public String mAddress; // // public String mPerson; // // public String mBody; // // public long mTimeStamp; // // public String mType; // // public int mStatus; // 0,未读,1,一读 // // public Sms(final long id, final String address, final String person, // final String body, final long date, final String type, // final int status) { // mId = id; // mAddress = address; // mPerson = person; // mBody = body; // mTimeStamp = date; // mType = type; // mStatus = status; // } // // public Sms(Parcel in) { // mId = in.readLong(); // mAddress = in.readString(); // mPerson = in.readString(); // mBody = in.readString(); // mTimeStamp = in.readLong(); // mType = in.readString(); // mStatus = in.readInt(); // } // // public Sms() { // // } // // @Override // public int describeContents() { // return 0; // } // // public final static Parcelable.Creator<Sms> CREATOR = new Creator<Sms>() { // // @Override // public Sms[] newArray(int size) { // return new Sms[size]; // } // // @Override // public Sms createFromParcel(Parcel source) { // return new Sms(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(mId); // dest.writeString(mAddress); // dest.writeString(mPerson); // dest.writeString(mBody); // dest.writeLong(mTimeStamp); // dest.writeString(mType); // dest.writeInt(mStatus); // } // // }
import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import com.xiaomi.alertsystem.data.Sms; import java.util.ArrayList; import java.util.List;
package com.xiaomi.alertsystem.utils; public class ReadLocalSmsHelper { public final static String SMS_URI_ALL = "content://sms/"; public final static String SMS_URI_INBOX = "content://sms/inbox"; public final static String SMS_URI_SEND = "content://sms/sent"; public final static String SMS_URI_DRAFT = "content://sms/draft"; public final static String SMS_URI_OUTBOX = "content://sms/outbox"; public final static String SMS_URI_FAILED = "content://sms/failed"; public final static String SMS_URI_QUEUED = "content://sms/queued"; public static class SmsColoumn { public final static String id = "_id"; public final static String address = "address"; public final static String person = "person"; public final static String body = "body"; public final static String date = "date"; public final static String type = "type"; } public final static String[] sProjection = new String[]{SmsColoumn.id, SmsColoumn.address, SmsColoumn.person, SmsColoumn.body, SmsColoumn.date, SmsColoumn.type};
// Path: src/com/xiaomi/alertsystem/data/Sms.java // public class Sms implements Parcelable { // public long mId; // // public String mAddress; // // public String mPerson; // // public String mBody; // // public long mTimeStamp; // // public String mType; // // public int mStatus; // 0,未读,1,一读 // // public Sms(final long id, final String address, final String person, // final String body, final long date, final String type, // final int status) { // mId = id; // mAddress = address; // mPerson = person; // mBody = body; // mTimeStamp = date; // mType = type; // mStatus = status; // } // // public Sms(Parcel in) { // mId = in.readLong(); // mAddress = in.readString(); // mPerson = in.readString(); // mBody = in.readString(); // mTimeStamp = in.readLong(); // mType = in.readString(); // mStatus = in.readInt(); // } // // public Sms() { // // } // // @Override // public int describeContents() { // return 0; // } // // public final static Parcelable.Creator<Sms> CREATOR = new Creator<Sms>() { // // @Override // public Sms[] newArray(int size) { // return new Sms[size]; // } // // @Override // public Sms createFromParcel(Parcel source) { // return new Sms(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(mId); // dest.writeString(mAddress); // dest.writeString(mPerson); // dest.writeString(mBody); // dest.writeLong(mTimeStamp); // dest.writeString(mType); // dest.writeInt(mStatus); // } // // } // Path: src/com/xiaomi/alertsystem/utils/ReadLocalSmsHelper.java import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import com.xiaomi.alertsystem.data.Sms; import java.util.ArrayList; import java.util.List; package com.xiaomi.alertsystem.utils; public class ReadLocalSmsHelper { public final static String SMS_URI_ALL = "content://sms/"; public final static String SMS_URI_INBOX = "content://sms/inbox"; public final static String SMS_URI_SEND = "content://sms/sent"; public final static String SMS_URI_DRAFT = "content://sms/draft"; public final static String SMS_URI_OUTBOX = "content://sms/outbox"; public final static String SMS_URI_FAILED = "content://sms/failed"; public final static String SMS_URI_QUEUED = "content://sms/queued"; public static class SmsColoumn { public final static String id = "_id"; public final static String address = "address"; public final static String person = "person"; public final static String body = "body"; public final static String date = "date"; public final static String type = "type"; } public final static String[] sProjection = new String[]{SmsColoumn.id, SmsColoumn.address, SmsColoumn.person, SmsColoumn.body, SmsColoumn.date, SmsColoumn.type};
public static List<Sms> querySms(final Context context, final Uri uri,
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/ui/AlertMainlAdapter.java
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // }
import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta;
/** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; public class AlertMainlAdapter extends BaseAdapter { private static final String TAG = "AlertMainlAdapter";
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // } // Path: src/com/xiaomi/alertsystem/ui/AlertMainlAdapter.java import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta; /** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com * @version V1.0 */ package com.xiaomi.alertsystem.ui; public class AlertMainlAdapter extends BaseAdapter { private static final String TAG = "AlertMainlAdapter";
private List<AlertMeta> mSms = null;
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/ui/AlertLevelAdapter.java
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // }
import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta; import java.util.List;
/** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com> * @version V1.0 */ package com.xiaomi.alertsystem.ui; //TODO:deprecated, will not be used public class AlertLevelAdapter extends BaseAdapter { private Activity mActivity;
// Path: src/com/xiaomi/alertsystem/data/AlertMeta.java // public class AlertMeta extends Sms implements Parcelable { // public static final String ALERT_LEVEL_PALL = "P"; // public static final String ALERT_LEVEL_P0 = "P0"; // public static final String ALERT_LEVEL_P1 = "P1"; // public static final String ALERT_LEVEL_P2 = "P2"; // public static final String ALERT_LEVEL_P3 = "P3"; // // public static final String ALERT_FLAG_OK = "OK"; // public static final String ALERT_FLAG_ERROR = "PROBLEM"; // // private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm"); // // public String mAlertLevel; // // public String mFlag; // 报警标志 // // public String mMachineName; // // public String mMachineIP; // // public String mMsg; // // public AlertMeta(final String level, final String flag, // final String machineName, final String machineIP, final String msg) { // // mAlertLevel = level; // mFlag = flag; // mMachineName = machineName; // mMachineIP = machineIP; // mMsg = msg; // } // // public String toString() { // return "(" + mId + ")" + mMsg.toString(); // } // // public AlertMeta(Parcel in) { // super(in); // mAlertLevel = in.readString(); // mFlag = in.readString(); // mMachineName = in.readString(); // mMachineIP = in.readString(); // mMsg = in.readString(); // } // // public AlertMeta() { // // } // // public String getAlertLevel() { // return mAlertLevel; // } // // public String getMachineName() { // return mMachineName; // } // // public String getMachineIP() { // return mMachineIP; // } // // public long getTimeStamp() { // return mTimeStamp; // } // // public String getProblem() { // return mBody; // } // // public String getDateTime() { // Date date = new Date(mTimeStamp); // return mSimpleDateFormat.format(date); // } // // public boolean isProblemMachine() { // if (TextUtils.isEmpty(mFlag)) { // return false; // } // return TextUtils.equals(mFlag, ALERT_FLAG_ERROR); // } // // public boolean isHighProblem() { // if (TextUtils.isEmpty(mAlertLevel)) { // return false; // } // // return TextUtils.equals(mAlertLevel, ALERT_LEVEL_P0); // } // // @Override // public boolean equals(Object o) { // AlertMeta alertMeta = (AlertMeta) o; // // if (o == null) { // return false; // } // // return alertMeta.mId == mId; // } // // public static final Parcelable.Creator<AlertMeta> CREATOR = new Creator<AlertMeta>() { // // @Override // public AlertMeta[] newArray(int size) { // return new AlertMeta[size]; // } // // @Override // public AlertMeta createFromParcel(Parcel source) { // return new AlertMeta(source); // } // }; // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeString(mAlertLevel); // dest.writeString(mFlag); // dest.writeString(mMachineName); // dest.writeString(mMachineIP); // dest.writeString(mMsg); // } // // } // Path: src/com/xiaomi/alertsystem/ui/AlertLevelAdapter.java import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.xiaomi.alertsystem.R; import com.xiaomi.alertsystem.data.AlertMeta; import java.util.List; /** * All rights Reserved, Designed By NoOps.me * Company: XIAOMI.COM * @author: * Xiaodong Pan <panxiaodong@xiaomi.com> * Wei Lai <laiwei@xiaomi.com> * @version V1.0 */ package com.xiaomi.alertsystem.ui; //TODO:deprecated, will not be used public class AlertLevelAdapter extends BaseAdapter { private Activity mActivity;
private List<AlertMeta> mList;
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/data/AlertManager.java
// Path: src/com/xiaomi/alertsystem/AlertSystemApplication.java // public class AlertSystemApplication extends Application { // public static final String TAG = "AlertSystemApplication"; // private static AlertSystemApplication sAlertSystemApplication; // // public static AlertSystemApplication getApp() { // return sAlertSystemApplication; // } // // @SuppressLint("NewApi") // @Override // public void onCreate() { // super.onCreate(); // // sAlertSystemApplication = (AlertSystemApplication) this // .getApplicationContext(); // SmsManager.init(getApplicationContext()); // startService(); // } // // public void startService(){ // Log.d(TAG, "start service"); // Intent i = new Intent(this, HandleSmsIntentService.class); // startService(i); // } // // public List<AlertMeta> parse(List<String> lines) { // List<AlertMeta> alertMetas = new ArrayList<AlertMeta>(); // // for (String str : lines) { // List<String> sms = AlertManager.getAlertManager().parse(str); // AlertMeta meta = AlertManager.getAlertManager().format(sms); // alertMetas.add(meta); // } // // return alertMetas; // } // } // // Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // }
import android.util.Log; import com.xiaomi.alertsystem.AlertSystemApplication; import com.xiaomi.alertsystem.data.Constants; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
while (matcher.find()) { list.add(matcher.group(1)); } // 然后尝试[] if (list.size() < 4) { list.clear(); pattern = Pattern.compile("\\[(.*?)\\]"); matcher = pattern.matcher(msg); while (matcher.find()) { list.add(matcher.group(1)); } } // 长度小于4,显示ParseError if (list.size() < 4) return null; else return list; } public AlertMeta format(List<String> lst) { AlertMeta meta = null; if (lst == null || lst.size() == 0) { return meta; } try { meta = new AlertMeta(); int levelIndex = 0; for (int i = 0; i < lst.size(); i++) {
// Path: src/com/xiaomi/alertsystem/AlertSystemApplication.java // public class AlertSystemApplication extends Application { // public static final String TAG = "AlertSystemApplication"; // private static AlertSystemApplication sAlertSystemApplication; // // public static AlertSystemApplication getApp() { // return sAlertSystemApplication; // } // // @SuppressLint("NewApi") // @Override // public void onCreate() { // super.onCreate(); // // sAlertSystemApplication = (AlertSystemApplication) this // .getApplicationContext(); // SmsManager.init(getApplicationContext()); // startService(); // } // // public void startService(){ // Log.d(TAG, "start service"); // Intent i = new Intent(this, HandleSmsIntentService.class); // startService(i); // } // // public List<AlertMeta> parse(List<String> lines) { // List<AlertMeta> alertMetas = new ArrayList<AlertMeta>(); // // for (String str : lines) { // List<String> sms = AlertManager.getAlertManager().parse(str); // AlertMeta meta = AlertManager.getAlertManager().format(sms); // alertMetas.add(meta); // } // // return alertMetas; // } // } // // Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // } // Path: src/com/xiaomi/alertsystem/data/AlertManager.java import android.util.Log; import com.xiaomi.alertsystem.AlertSystemApplication; import com.xiaomi.alertsystem.data.Constants; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; while (matcher.find()) { list.add(matcher.group(1)); } // 然后尝试[] if (list.size() < 4) { list.clear(); pattern = Pattern.compile("\\[(.*?)\\]"); matcher = pattern.matcher(msg); while (matcher.find()) { list.add(matcher.group(1)); } } // 长度小于4,显示ParseError if (list.size() < 4) return null; else return list; } public AlertMeta format(List<String> lst) { AlertMeta meta = null; if (lst == null || lst.size() == 0) { return meta; } try { meta = new AlertMeta(); int levelIndex = 0; for (int i = 0; i < lst.size(); i++) {
if (Constants.NOTIFICATION_LEVEL.contains(lst.get(i)
xiaomi-sa/alertsystem
src/com/xiaomi/alertsystem/utils/CommonUtils.java
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.xiaomi.alertsystem.data.Constants; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.BaseColumns;
package com.xiaomi.alertsystem.utils; public class CommonUtils { private static String AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:17.0) Gecko/17.0 Firefox/17."; private static String defaultHome; public static boolean mkdir(String path) { File file = new File(path); if (file.isDirectory()) return true; else { boolean creadok = file.mkdirs(); if (creadok) { return true; } else { return false; } } } public static String getSdcardPath() { String sdcardPath = Environment.getExternalStorageDirectory() .getAbsolutePath(); return sdcardPath; } public static void setDefaultHome() { String sdcard = getSdcardPath();
// Path: src/com/xiaomi/alertsystem/data/Constants.java // public class Constants { // public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // // broadcast: sms updated // public static final String sActSmsInserted = "com.xiaomi.alertsystem.SMS_INSERTED"; // // // intent: start activity thread // public static final String sActSmsThread = "com.xiaomi.alertsystem.SMS_THREAD"; // public static final String TIELE_INTENT = "title_intent"; // public static final String KEY = "key"; // public static final String HOST = "host"; // public static final String URL_UPDATE = "http://xbox.pt.xiaomi.com/monitor/apk/alertsystem/update?ver="; // public static final String APP_DIR = "alertsystem/"; // public static final String DEFAULT_DIR = "/sdcard/"; // // // // 报警方式 // public static final int NOTIFICATION_NONE = 0; // public static final int NOTIFICATION_SOUND = 1; // public static final int NOTIFICATION_VIBRATE = 2; // public static final int NOTIFICATION_SOUND_VIBRATE = 3; // public static final int NOTIFICATION_BUBBLE = 4; // // // 版本消息提示 // public static final int MSG_VER_ERROR = 1000; // public static final int MSG_VER_UPDATE = 1001; // public static final int MSG_VER_NONEED = 1002; // // public static final String[] NOTIFICATION = { "不提醒", "声音", "振动", "声音振动", // "通知栏" }; // public static ArrayList<String> NOTIFICATION_LEVEL = new ArrayList( // Arrays.asList("P", "P0", "P1", "P2", "P3")); // // // *******************拦截号码********************* // public static ArrayList<String> DEFAULT_PHONE = new ArrayList( // Arrays.asList("10657520300931689", "10690269222", "15011518472", // "951312330315")); // // public static final String P0_SOUND_KEY = "pref_p0_notification"; // public static final String P1_SOUND_KEY = "pref_p1_notification"; // public static final String P2_SOUND_KEY = "pref_p2_notification"; // public static final String P3_SOUND_KEY = "pref_p3_notification"; // public static final String P4_SOUND_KEY = "pref_p4_notification"; // public static final String P5_SOUND_KEY = "pref_p5_notification"; // // public static final String BROADCAST_TYPE = "com.xiaomi.alertsystem.broadcast_type"; // public static final String BROADCAST_SMS = "com.xiaomi.alertsystem.broadcast_sms"; // // 数据刷新方式 // public static final int DATA_REFREASH = 1; // public static final int DATA_CHANGE = 2; // public static final int DATA_REMOVE = 3; // public static final int DATA_LIST_CHANGE = 4; // // } // Path: src/com/xiaomi/alertsystem/utils/CommonUtils.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.xiaomi.alertsystem.data.Constants; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.BaseColumns; package com.xiaomi.alertsystem.utils; public class CommonUtils { private static String AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:17.0) Gecko/17.0 Firefox/17."; private static String defaultHome; public static boolean mkdir(String path) { File file = new File(path); if (file.isDirectory()) return true; else { boolean creadok = file.mkdirs(); if (creadok) { return true; } else { return false; } } } public static String getSdcardPath() { String sdcardPath = Environment.getExternalStorageDirectory() .getAbsolutePath(); return sdcardPath; } public static void setDefaultHome() { String sdcard = getSdcardPath();
String path = sdcard + "/" + Constants.APP_DIR + "/";
OWASP/OWASP-WebScarab
src/org/owasp/webscarab/plugin/spider/SpiderModel.java
// Path: src/org/owasp/webscarab/model/Preferences.java // public class Preferences { // // static Properties _props = new Properties(); // private static String _location = null; // // /** Creates a new instance of Preferences */ // private Preferences() { // } // // public static Properties getPreferences() { // return _props; // } // // public static void loadPreferences(String file) throws IOException { // // If we are given a filename to load, use it, otherwise // // look for a props file in the user's home directory // // if the file does not exist, use the standard defaults // // if (file == null) { // String sep = System.getProperty("file.separator"); // String home = System.getProperty("user.home"); // _location = home + sep + "WebScarab.properties"; // } else { // _location = file; // } // // try { // Properties props = new Properties(); // InputStream is = new FileInputStream(_location); // props.load(is); // _props = props; // } catch (FileNotFoundException fnfe) { // // we'll just use the defaults // } // } // // public static void savePreferences() throws IOException { // FileOutputStream fos = new FileOutputStream(_location); // _props.store(fos,"WebScarab Properties"); // fos.close(); // } // // public static void setPreference(String key, String value) { // _props.setProperty(key, value); // } // // public static String getPreference(String key) { // String result = System.getProperty(key); // if (result == null) // result = _props.getProperty(key); // return result; // } // // public static String getPreference(String key, String defaultValue) { // String result = getPreference(key); // if (result == null) // result = defaultValue; // return result; // } // // public static String remove(String key) { // return (String) _props.remove(key); // } // // }
import org.owasp.webscarab.model.UrlModel; import org.owasp.webscarab.model.Cookie; import org.owasp.webscarab.model.NamedValue; import org.owasp.webscarab.model.HttpUrl; import org.owasp.webscarab.model.Preferences; import org.owasp.webscarab.model.FrameworkModel; import org.owasp.webscarab.model.FilteredUrlModel; import org.owasp.webscarab.plugin.AbstractPluginModel; import java.util.List; import java.util.LinkedList; import java.util.logging.Logger;
/* * SpiderModel.java * * Created on 04 March 2005, 03:11 */ package org.owasp.webscarab.plugin.spider; /** * * @author rogan */ public class SpiderModel extends AbstractPluginModel { private FrameworkModel _model; private SpiderUrlModel _urlModel; private List<Link> _linkQueue = new LinkedList<Link>(); private String _allowedDomains = null; private String _forbiddenPaths = null; private boolean _recursive = false; private boolean _cookieSync = false; private NamedValue[] _extraHeaders = null; private Logger _logger = Logger.getLogger(getClass().getName()); /** Creates a new instance of SpiderModel */ public SpiderModel(FrameworkModel model) { _model = model; _urlModel = new SpiderUrlModel(_model.getUrlModel()); parseProperties(); } public UrlModel getUrlModel() { return _urlModel; } public boolean isUnseen(HttpUrl url) { return _model.getUrlProperty(url, "METHODS") == null; } public boolean isForbidden(HttpUrl url) { if (_forbiddenPaths != null && !_forbiddenPaths.equals("")) { try { return url.toString().matches(getForbiddenPaths()); } catch (Exception e) { } } return false; } public void addUnseenLink(HttpUrl url, HttpUrl referer) { if (url == null) { return; } if (isUnseen(url)) { String first = _model.getUrlProperty(url, "REFERER"); if (first == null || first.equals("")) { _model.setUrlProperty(url, "REFERER", referer.toString()); } } } public void queueLink(Link link) { // _logger.info("Queueing " + link); try { _model.readLock().acquire(); _linkQueue.add(link); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } // _logger.info("Done queuing " + link); } public Link dequeueLink() { // _logger.info("Dequeueing a link"); Link link = null; try { _model.readLock().acquire(); if (_linkQueue.size() > 0) link = _linkQueue.remove(0); if (_linkQueue.size() == 0) { setStatus("Idle"); } else { setStatus(_linkQueue.size() + " links remaining"); } } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); // _logger.info("Done dequeuing a link " + link); } return link; } public void clearLinkQueue() { try { _model.readLock().acquire(); _linkQueue.clear(); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } } public int getQueuedLinkCount() { try { _model.readLock().acquire(); return _linkQueue.size(); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } return 0; } public Cookie[] getCookiesForUrl(HttpUrl url) { return _model.getCookiesForUrl(url); } public void addCookie(Cookie cookie) { _model.addCookie(cookie); } public void parseProperties() { String prop = "Spider.domains";
// Path: src/org/owasp/webscarab/model/Preferences.java // public class Preferences { // // static Properties _props = new Properties(); // private static String _location = null; // // /** Creates a new instance of Preferences */ // private Preferences() { // } // // public static Properties getPreferences() { // return _props; // } // // public static void loadPreferences(String file) throws IOException { // // If we are given a filename to load, use it, otherwise // // look for a props file in the user's home directory // // if the file does not exist, use the standard defaults // // if (file == null) { // String sep = System.getProperty("file.separator"); // String home = System.getProperty("user.home"); // _location = home + sep + "WebScarab.properties"; // } else { // _location = file; // } // // try { // Properties props = new Properties(); // InputStream is = new FileInputStream(_location); // props.load(is); // _props = props; // } catch (FileNotFoundException fnfe) { // // we'll just use the defaults // } // } // // public static void savePreferences() throws IOException { // FileOutputStream fos = new FileOutputStream(_location); // _props.store(fos,"WebScarab Properties"); // fos.close(); // } // // public static void setPreference(String key, String value) { // _props.setProperty(key, value); // } // // public static String getPreference(String key) { // String result = System.getProperty(key); // if (result == null) // result = _props.getProperty(key); // return result; // } // // public static String getPreference(String key, String defaultValue) { // String result = getPreference(key); // if (result == null) // result = defaultValue; // return result; // } // // public static String remove(String key) { // return (String) _props.remove(key); // } // // } // Path: src/org/owasp/webscarab/plugin/spider/SpiderModel.java import org.owasp.webscarab.model.UrlModel; import org.owasp.webscarab.model.Cookie; import org.owasp.webscarab.model.NamedValue; import org.owasp.webscarab.model.HttpUrl; import org.owasp.webscarab.model.Preferences; import org.owasp.webscarab.model.FrameworkModel; import org.owasp.webscarab.model.FilteredUrlModel; import org.owasp.webscarab.plugin.AbstractPluginModel; import java.util.List; import java.util.LinkedList; import java.util.logging.Logger; /* * SpiderModel.java * * Created on 04 March 2005, 03:11 */ package org.owasp.webscarab.plugin.spider; /** * * @author rogan */ public class SpiderModel extends AbstractPluginModel { private FrameworkModel _model; private SpiderUrlModel _urlModel; private List<Link> _linkQueue = new LinkedList<Link>(); private String _allowedDomains = null; private String _forbiddenPaths = null; private boolean _recursive = false; private boolean _cookieSync = false; private NamedValue[] _extraHeaders = null; private Logger _logger = Logger.getLogger(getClass().getName()); /** Creates a new instance of SpiderModel */ public SpiderModel(FrameworkModel model) { _model = model; _urlModel = new SpiderUrlModel(_model.getUrlModel()); parseProperties(); } public UrlModel getUrlModel() { return _urlModel; } public boolean isUnseen(HttpUrl url) { return _model.getUrlProperty(url, "METHODS") == null; } public boolean isForbidden(HttpUrl url) { if (_forbiddenPaths != null && !_forbiddenPaths.equals("")) { try { return url.toString().matches(getForbiddenPaths()); } catch (Exception e) { } } return false; } public void addUnseenLink(HttpUrl url, HttpUrl referer) { if (url == null) { return; } if (isUnseen(url)) { String first = _model.getUrlProperty(url, "REFERER"); if (first == null || first.equals("")) { _model.setUrlProperty(url, "REFERER", referer.toString()); } } } public void queueLink(Link link) { // _logger.info("Queueing " + link); try { _model.readLock().acquire(); _linkQueue.add(link); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } // _logger.info("Done queuing " + link); } public Link dequeueLink() { // _logger.info("Dequeueing a link"); Link link = null; try { _model.readLock().acquire(); if (_linkQueue.size() > 0) link = _linkQueue.remove(0); if (_linkQueue.size() == 0) { setStatus("Idle"); } else { setStatus(_linkQueue.size() + " links remaining"); } } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); // _logger.info("Done dequeuing a link " + link); } return link; } public void clearLinkQueue() { try { _model.readLock().acquire(); _linkQueue.clear(); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } } public int getQueuedLinkCount() { try { _model.readLock().acquire(); return _linkQueue.size(); } catch (InterruptedException ie) { _logger.warning("Interrupted waiting for the read lock! " + ie.getMessage()); } finally { _model.readLock().release(); } return 0; } public Cookie[] getCookiesForUrl(HttpUrl url) { return _model.getCookiesForUrl(url); } public void addCookie(Cookie cookie) { _model.addCookie(cookie); } public void parseProperties() { String prop = "Spider.domains";
String value = Preferences.getPreference(prop, ".*localhost.*");
OWASP/OWASP-WebScarab
src/org/owasp/webscarab/plugin/saml/swing/SamlReplayConversationAction.java
// Path: src/org/owasp/webscarab/model/ConversationID.java // public class ConversationID implements Comparable<ConversationID> { // // private static Object _lock = new Object(); // private static int _next = 1; // // private int _id; // // /** // * Creates a new instance of ConversationID. Each ConversationID created using this // * constructor will be unique (currently based on an incrementing integer value) // */ // public ConversationID() { // synchronized(_lock) { // _id = _next++; // } // } // // public ConversationID(int id) { // synchronized (_lock) { // _id = id; // if (_id >= _next) { // _next = _id + 1; // } else if (_id <= 0) { // throw new IllegalArgumentException("Cannot use a negative ConversationID"); // } // } // } // // /** // * creates a Conversation ID based on the string provided. // * The next no-parameter ConversationID created will be "greater" than this one. // * @param id a string representation of the ConversationID // */ // public ConversationID(String id) { // this(Integer.parseInt(id.trim())); // } // // /** // * resets the ConversationID counter to zero. // */ // public static void reset() { // synchronized(_lock) { // _next = 1; // } // } // // protected int getID() { // return _id; // } // // /** // * shows a string representation of the ConversationID // * @return a string representation // */ // public String toString() { // return Integer.toString(_id); // } // // /** // * compares this ConversationID to another // * @param o the other ConversationID to compare to // * @return true if they are equal, false otherwise // */ // public boolean equals(Object o) { // if (o == null || ! (o instanceof ConversationID)) return false; // return _id == ((ConversationID)o).getID(); // } // // /** // * // * @return // */ // public int hashCode() { // return _id; // } // // /** // * compares this ConversationID to another // * @param o the other ConversationID to compare to // * @return -1, 0 or 1 if this ConversationID is less than, equal to, or greater than the supplied parameter // */ // public int compareTo(ConversationID o) { // int thatid = o.getID(); // return _id - thatid; // } // // }
import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import org.owasp.webscarab.model.ConversationID; import org.owasp.webscarab.plugin.saml.SamlProxy;
/*********************************************************************** * * $CVSHeader$ * * This file is part of WebScarab, an Open Web Application Security * Project utility. For details, please see http://www.owasp.org/ * * Copyright (c) 2010 FedICT * Copyright (c) 2010 Frank Cornelis <info@frankcornelis.be> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Getting Source * ============== * * Source for this application is maintained at Sourceforge.net, a * repository for free software projects. * * For details, please see http://www.sourceforge.net/projects/owasp * */ package org.owasp.webscarab.plugin.saml.swing; /** * * @author Frank Cornelis */ public final class SamlReplayConversationAction extends AbstractAction { private final SamlProxy samlProxy; public SamlReplayConversationAction(SamlProxy samlProxy) { this.samlProxy = samlProxy; putValue(NAME, "Use for replay attack"); putValue(SHORT_DESCRIPTION, "Use this SAML Response for replay attack"); } @Override public void actionPerformed(ActionEvent e) { Object o = getValue("SAML-RESPONSE");
// Path: src/org/owasp/webscarab/model/ConversationID.java // public class ConversationID implements Comparable<ConversationID> { // // private static Object _lock = new Object(); // private static int _next = 1; // // private int _id; // // /** // * Creates a new instance of ConversationID. Each ConversationID created using this // * constructor will be unique (currently based on an incrementing integer value) // */ // public ConversationID() { // synchronized(_lock) { // _id = _next++; // } // } // // public ConversationID(int id) { // synchronized (_lock) { // _id = id; // if (_id >= _next) { // _next = _id + 1; // } else if (_id <= 0) { // throw new IllegalArgumentException("Cannot use a negative ConversationID"); // } // } // } // // /** // * creates a Conversation ID based on the string provided. // * The next no-parameter ConversationID created will be "greater" than this one. // * @param id a string representation of the ConversationID // */ // public ConversationID(String id) { // this(Integer.parseInt(id.trim())); // } // // /** // * resets the ConversationID counter to zero. // */ // public static void reset() { // synchronized(_lock) { // _next = 1; // } // } // // protected int getID() { // return _id; // } // // /** // * shows a string representation of the ConversationID // * @return a string representation // */ // public String toString() { // return Integer.toString(_id); // } // // /** // * compares this ConversationID to another // * @param o the other ConversationID to compare to // * @return true if they are equal, false otherwise // */ // public boolean equals(Object o) { // if (o == null || ! (o instanceof ConversationID)) return false; // return _id == ((ConversationID)o).getID(); // } // // /** // * // * @return // */ // public int hashCode() { // return _id; // } // // /** // * compares this ConversationID to another // * @param o the other ConversationID to compare to // * @return -1, 0 or 1 if this ConversationID is less than, equal to, or greater than the supplied parameter // */ // public int compareTo(ConversationID o) { // int thatid = o.getID(); // return _id - thatid; // } // // } // Path: src/org/owasp/webscarab/plugin/saml/swing/SamlReplayConversationAction.java import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import org.owasp.webscarab.model.ConversationID; import org.owasp.webscarab.plugin.saml.SamlProxy; /*********************************************************************** * * $CVSHeader$ * * This file is part of WebScarab, an Open Web Application Security * Project utility. For details, please see http://www.owasp.org/ * * Copyright (c) 2010 FedICT * Copyright (c) 2010 Frank Cornelis <info@frankcornelis.be> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Getting Source * ============== * * Source for this application is maintained at Sourceforge.net, a * repository for free software projects. * * For details, please see http://www.sourceforge.net/projects/owasp * */ package org.owasp.webscarab.plugin.saml.swing; /** * * @author Frank Cornelis */ public final class SamlReplayConversationAction extends AbstractAction { private final SamlProxy samlProxy; public SamlReplayConversationAction(SamlProxy samlProxy) { this.samlProxy = samlProxy; putValue(NAME, "Use for replay attack"); putValue(SHORT_DESCRIPTION, "Use this SAML Response for replay attack"); } @Override public void actionPerformed(ActionEvent e) { Object o = getValue("SAML-RESPONSE");
if (o == null || !(o instanceof ConversationID)) {
OWASP/OWASP-WebScarab
src/org/owasp/webscarab/plugin/ScriptManager.java
// Path: src/org/owasp/webscarab/model/Preferences.java // public class Preferences { // // static Properties _props = new Properties(); // private static String _location = null; // // /** Creates a new instance of Preferences */ // private Preferences() { // } // // public static Properties getPreferences() { // return _props; // } // // public static void loadPreferences(String file) throws IOException { // // If we are given a filename to load, use it, otherwise // // look for a props file in the user's home directory // // if the file does not exist, use the standard defaults // // if (file == null) { // String sep = System.getProperty("file.separator"); // String home = System.getProperty("user.home"); // _location = home + sep + "WebScarab.properties"; // } else { // _location = file; // } // // try { // Properties props = new Properties(); // InputStream is = new FileInputStream(_location); // props.load(is); // _props = props; // } catch (FileNotFoundException fnfe) { // // we'll just use the defaults // } // } // // public static void savePreferences() throws IOException { // FileOutputStream fos = new FileOutputStream(_location); // _props.store(fos,"WebScarab Properties"); // fos.close(); // } // // public static void setPreference(String key, String value) { // _props.setProperty(key, value); // } // // public static String getPreference(String key) { // String result = System.getProperty(key); // if (result == null) // result = _props.getProperty(key); // return result; // } // // public static String getPreference(String key, String defaultValue) { // String result = getPreference(key); // if (result == null) // result = defaultValue; // return result; // } // // public static String remove(String key) { // return (String) _props.remove(key); // } // // }
import java.io.File; import java.io.IOException; import org.apache.bsf.BSFManager; import org.apache.bsf.BSFException; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.logging.Logger; import javax.swing.event.EventListenerList; import org.owasp.webscarab.model.Preferences;
/* * ScriptManager.java * * Created on 07 January 2005, 04:42 */ package org.owasp.webscarab.plugin; /** * * @author rogan */ public class ScriptManager { private BSFManager _bsfManager; private TreeMap<String, Hook[]> _hooks = new TreeMap<String, Hook[]>(); private EventListenerList _listeners = new EventListenerList(); private Logger _logger = Logger.getLogger(getClass().getName()); /** Creates a new instance of ScriptManager */ public ScriptManager(Framework framework) { try { _bsfManager = new BSFManager(); _bsfManager.declareBean("framework", framework, framework.getClass()); _bsfManager.declareBean("out", System.out, System.out.getClass()); _bsfManager.declareBean("err", System.err, System.out.getClass()); } catch (BSFException bsfe) { _logger.severe("Declaring a bean should not throw an exception! " + bsfe); } } public void addScriptListener(ScriptListener listener) { synchronized(_listeners) { _listeners.add(ScriptListener.class, listener); } } public void removeScriptListener(ScriptListener listener) { synchronized(_listeners) { _listeners.remove(ScriptListener.class, listener); } } public void registerHooks(String pluginName, Hook[] hooks) { if (hooks != null && hooks.length > 0) { _hooks.put(pluginName, hooks); for (int i=0; i<hooks.length; i++) { hooks[i].setBSFManager(_bsfManager); } fireHooksChanged(); } } public int getPluginCount() { return _hooks.size(); } public String getPlugin(int i) { String[] plugins = _hooks.keySet().toArray(new String[0]); return plugins[i]; } public int getHookCount(String plugin) { Hook[] hooks = _hooks.get(plugin); if (hooks == null) return 0; return hooks.length; } public Hook getHook(String plugin, int i) { Hook[] hooks = _hooks.get(plugin); if (hooks == null) return null; return hooks[i]; } public void addScript(String plugin, Hook hook, Script script, int position) throws BSFException { String language = BSFManager.getLangFromFilename(script.getFile().getName()); if (language != null) { script.setLanguage(language); script.setEnabled(true); hook.addScript(script, position); fireScriptAdded(plugin, hook, script); } } public void addScript(String plugin, Hook hook, Script script) throws BSFException { addScript(plugin, hook, script, hook.getScriptCount()); } public void setEnabled(String plugin, Hook hook, Script script, boolean enabled) { script.setEnabled(enabled); fireScriptChanged(plugin, hook, script); } public void removeScript(String plugin, Hook hook, Script script) { int count = hook.getScriptCount(); for (int i=0; i<count; i++) { Script s = hook.getScript(i); if (s == script) { hook.removeScript(i); fireScriptRemoved(plugin, hook, script); return; } } } public void loadScripts() { Iterator<Map.Entry<String, Hook[]>> hookIt = _hooks.entrySet().iterator(); while (hookIt.hasNext()) { Map.Entry<String, Hook[]> entry = hookIt.next(); String plugin = entry.getKey(); Hook[] hooks = entry.getValue(); if (hooks != null) { for (int i=0; i<hooks.length; i++) { for (int j=0; j<hooks[i].getScriptCount(); j++) hooks[i].removeScript(j); int j=0;
// Path: src/org/owasp/webscarab/model/Preferences.java // public class Preferences { // // static Properties _props = new Properties(); // private static String _location = null; // // /** Creates a new instance of Preferences */ // private Preferences() { // } // // public static Properties getPreferences() { // return _props; // } // // public static void loadPreferences(String file) throws IOException { // // If we are given a filename to load, use it, otherwise // // look for a props file in the user's home directory // // if the file does not exist, use the standard defaults // // if (file == null) { // String sep = System.getProperty("file.separator"); // String home = System.getProperty("user.home"); // _location = home + sep + "WebScarab.properties"; // } else { // _location = file; // } // // try { // Properties props = new Properties(); // InputStream is = new FileInputStream(_location); // props.load(is); // _props = props; // } catch (FileNotFoundException fnfe) { // // we'll just use the defaults // } // } // // public static void savePreferences() throws IOException { // FileOutputStream fos = new FileOutputStream(_location); // _props.store(fos,"WebScarab Properties"); // fos.close(); // } // // public static void setPreference(String key, String value) { // _props.setProperty(key, value); // } // // public static String getPreference(String key) { // String result = System.getProperty(key); // if (result == null) // result = _props.getProperty(key); // return result; // } // // public static String getPreference(String key, String defaultValue) { // String result = getPreference(key); // if (result == null) // result = defaultValue; // return result; // } // // public static String remove(String key) { // return (String) _props.remove(key); // } // // } // Path: src/org/owasp/webscarab/plugin/ScriptManager.java import java.io.File; import java.io.IOException; import org.apache.bsf.BSFManager; import org.apache.bsf.BSFException; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.logging.Logger; import javax.swing.event.EventListenerList; import org.owasp.webscarab.model.Preferences; /* * ScriptManager.java * * Created on 07 January 2005, 04:42 */ package org.owasp.webscarab.plugin; /** * * @author rogan */ public class ScriptManager { private BSFManager _bsfManager; private TreeMap<String, Hook[]> _hooks = new TreeMap<String, Hook[]>(); private EventListenerList _listeners = new EventListenerList(); private Logger _logger = Logger.getLogger(getClass().getName()); /** Creates a new instance of ScriptManager */ public ScriptManager(Framework framework) { try { _bsfManager = new BSFManager(); _bsfManager.declareBean("framework", framework, framework.getClass()); _bsfManager.declareBean("out", System.out, System.out.getClass()); _bsfManager.declareBean("err", System.err, System.out.getClass()); } catch (BSFException bsfe) { _logger.severe("Declaring a bean should not throw an exception! " + bsfe); } } public void addScriptListener(ScriptListener listener) { synchronized(_listeners) { _listeners.add(ScriptListener.class, listener); } } public void removeScriptListener(ScriptListener listener) { synchronized(_listeners) { _listeners.remove(ScriptListener.class, listener); } } public void registerHooks(String pluginName, Hook[] hooks) { if (hooks != null && hooks.length > 0) { _hooks.put(pluginName, hooks); for (int i=0; i<hooks.length; i++) { hooks[i].setBSFManager(_bsfManager); } fireHooksChanged(); } } public int getPluginCount() { return _hooks.size(); } public String getPlugin(int i) { String[] plugins = _hooks.keySet().toArray(new String[0]); return plugins[i]; } public int getHookCount(String plugin) { Hook[] hooks = _hooks.get(plugin); if (hooks == null) return 0; return hooks.length; } public Hook getHook(String plugin, int i) { Hook[] hooks = _hooks.get(plugin); if (hooks == null) return null; return hooks[i]; } public void addScript(String plugin, Hook hook, Script script, int position) throws BSFException { String language = BSFManager.getLangFromFilename(script.getFile().getName()); if (language != null) { script.setLanguage(language); script.setEnabled(true); hook.addScript(script, position); fireScriptAdded(plugin, hook, script); } } public void addScript(String plugin, Hook hook, Script script) throws BSFException { addScript(plugin, hook, script, hook.getScriptCount()); } public void setEnabled(String plugin, Hook hook, Script script, boolean enabled) { script.setEnabled(enabled); fireScriptChanged(plugin, hook, script); } public void removeScript(String plugin, Hook hook, Script script) { int count = hook.getScriptCount(); for (int i=0; i<count; i++) { Script s = hook.getScript(i); if (s == script) { hook.removeScript(i); fireScriptRemoved(plugin, hook, script); return; } } } public void loadScripts() { Iterator<Map.Entry<String, Hook[]>> hookIt = _hooks.entrySet().iterator(); while (hookIt.hasNext()) { Map.Entry<String, Hook[]> entry = hookIt.next(); String plugin = entry.getKey(); Hook[] hooks = entry.getValue(); if (hooks != null) { for (int i=0; i<hooks.length; i++) { for (int j=0; j<hooks[i].getScriptCount(); j++) hooks[i].removeScript(j); int j=0;
String scriptName = Preferences.getPreference(hooks[i].getName()+"."+j+".name");
NicolaasWeideman/RegexStaticAnalysis
src/main/java/matcher/driver/MatcherDriver.java
// Path: src/main/java/analysis/AnalysisSettings.java // public static enum NFAConstruction { // THOMPSON, // JAVA; // }
import matcher.*; import regexcompiler.*; import analysis.AnalysisSettings.NFAConstruction;
package matcher.driver; public class MatcherDriver { public static void main(String args[]) { if (args.length < 2) { System.out.println("usage: java MatcherDriver <regex> <input string>"); System.exit(0); } String pattern = args[0]; String inputString = args[1];
// Path: src/main/java/analysis/AnalysisSettings.java // public static enum NFAConstruction { // THOMPSON, // JAVA; // } // Path: src/main/java/matcher/driver/MatcherDriver.java import matcher.*; import regexcompiler.*; import analysis.AnalysisSettings.NFAConstruction; package matcher.driver; public class MatcherDriver { public static void main(String args[]) { if (args.length < 2) { System.out.println("usage: java MatcherDriver <regex> <input string>"); System.exit(0); } String pattern = args[0]; String inputString = args[1];
MyPattern myPattern = MyPattern.compile(pattern, NFAConstruction.JAVA);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override
public String process(List<RegexToken> tokenStream) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) {
if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) {
RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i];
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i];
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i];
if (factorToken.getFactorType() == FactorType.GROUP) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i]; if (factorToken.getFactorType() == FactorType.GROUP) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i]; if (factorToken.getFactorType() == FactorType.GROUP) {
GroupFactor groupFactor = (GroupFactor) factorToken;
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseLookaroundExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i]; if (factorToken.getFactorType() == FactorType.GROUP) { GroupFactor groupFactor = (GroupFactor) factorToken;
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class GroupFactor extends RegexFactor<List<RegexToken>> { // // // private int level; // public int getLevel() { // return level; // } // // public GroupFactor(List<RegexToken> factorContent, GroupType groupType) { // super(factorContent); // this.groupType = groupType; // } // // public GroupFactor(String processedContent, GroupType groupType, int level) { // super(ParsingPreprocessor.tokenize(processedContent, level + 1)); // this.level = level; // this.groupType = groupType; // } // // @Override // public FactorType getFactorType() { // return FactorType.GROUP; // } // // private GroupType groupType; // // public GroupType getGroupType() { // return groupType; // } // // private String groupPrefix() { // switch (groupType) { // case NORMAL: // return ""; // case NONCAPTURING: // return "?:"; // case POSLOOKAHEAD: // return "?="; // case POSLOOKBEHIND: // return "?<="; // case NEGLOOKAHEAD: // return "?!"; // case NEGLOOKBEHIND: // return "?<!"; // default: // throw new AssertionError("Unknown group type."); // } // } // // @Override // public String toString() { // String type = groupPrefix(); // return "Group( " + type + " " + factorContent + " )"; // } // // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // @Override // public String getRepresentation() { // String type = groupPrefix(); // StringBuilder contentBuilder = new StringBuilder(); // for (RegexToken rt : factorContent) { // contentBuilder.append(rt.getRepresentation()); // } // return "(" + type + contentBuilder.toString() + ")"; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof GroupFactor)) { // return false; // } // // GroupFactor ro = (GroupFactor) o; // return ro.factorContent.equals(factorContent); // } // // @Override // public int hashCode() { // return groupType.hashCode() * 13 + factorContent.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static abstract class RegexFactor<FactorContentType> implements RegexToken { // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // protected FactorContentType factorContent; // // public FactorContentType getFactorContent() { // return factorContent; // } // // public RegexFactor(FactorContentType factorContent) { // this.factorContent = factorContent; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_FACTOR; // } // // public abstract FactorType getFactorType(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum GroupType { // NORMAL, NONCAPTURING, POSLOOKAHEAD, POSLOOKBEHIND, NEGLOOKAHEAD, NEGLOOKBEHIND // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum FactorType { // CHARACTER_CLASS, SINGLE_CHARACTER, ESCAPED_CHARACTER, GROUP, WILD_CARD // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseLookaroundExpansion.java import java.util.List; import preprocessor.ParsingPreprocessor.GroupFactor; import preprocessor.ParsingPreprocessor.RegexFactor; import preprocessor.ParsingPreprocessor.GroupFactor.GroupType; import preprocessor.ParsingPreprocessor.RegexFactor.FactorType; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseLookaroundExpansion implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_FACTOR) { RegexFactor<?> factorToken = (RegexFactor<?>) tokens[i]; if (factorToken.getFactorType() == FactorType.GROUP) { GroupFactor groupFactor = (GroupFactor) factorToken;
GroupType groupType = groupFactor.getGroupType();
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseCountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseCountClosureOperatorExpansion extends OperatorExpansionRule { private final int CONSTANT_CUTOFF = 32; private final int BOUND_DIFF_CUTOFF = Integer.MAX_VALUE; @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseCountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseCountClosureOperatorExpansion extends OperatorExpansionRule { private final int CONSTANT_CUTOFF = 32; private final int BOUND_DIFF_CUTOFF = Integer.MAX_VALUE; @Override
protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/NonpreciseCountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class NonpreciseCountClosureOperatorExpansion extends OperatorExpansionRule { private final int CONSTANT_CUTOFF = 32; private final int BOUND_DIFF_CUTOFF = Integer.MAX_VALUE; @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/NonpreciseCountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class NonpreciseCountClosureOperatorExpansion extends OperatorExpansionRule { private final int CONSTANT_CUTOFF = 32; private final int BOUND_DIFF_CUTOFF = Integer.MAX_VALUE; @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
CountClosureOperator cco = (CountClosureOperator) operator;
NicolaasWeideman/RegexStaticAnalysis
src/main/java/regexcompiler/NFACreator.java
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // }
import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator;
package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2);
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // } // Path: src/main/java/regexcompiler/NFACreator.java import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator; package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2);
public NFAGraph starNFA(NFAGraph m, RegexStarOperator starOperator);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/regexcompiler/NFACreator.java
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // }
import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator;
package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph starNFA(NFAGraph m, RegexStarOperator starOperator);
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // } // Path: src/main/java/regexcompiler/NFACreator.java import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator; package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph starNFA(NFAGraph m, RegexStarOperator starOperator);
public NFAGraph plusNFA(NFAGraph m, RegexPlusOperator plusOperator);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/regexcompiler/NFACreator.java
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // }
import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator;
package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph starNFA(NFAGraph m, RegexStarOperator starOperator); public NFAGraph plusNFA(NFAGraph m, RegexPlusOperator plusOperator); public NFAGraph countClosureNFA(NFAGraph m, RegexCountClosureOperator countClosureOperator);
// Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexPlusOperator extends RegexQuantifiableOperator { // // public RegexPlusOperator(QuantifierType quantifierType, int index) { // super(OperatorType.PLUS, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexQuestionMarkOperator extends RegexQuantifiableOperator { // // public RegexQuestionMarkOperator(QuantifierType quantifierType, int index) { // super(OperatorType.QUESTION_MARK, quantifierType, index); // } // // } // // Path: src/main/java/regexcompiler/RegexQuantifiableOperator.java // public static class RegexStarOperator extends RegexQuantifiableOperator { // // public RegexStarOperator(QuantifierType quantifierType, int index) { // super(OperatorType.STAR, quantifierType, index); // } // // } // Path: src/main/java/regexcompiler/NFACreator.java import nfa.*; import regexcompiler.RegexQuantifiableOperator.RegexPlusOperator; import regexcompiler.RegexQuantifiableOperator.RegexQuestionMarkOperator; import regexcompiler.RegexQuantifiableOperator.RegexStarOperator; package regexcompiler; public interface NFACreator { public NFAGraph createBaseCaseEmpty(); public NFAGraph createBaseCaseLookAround(NFAVertexND lookAroundState); public NFAGraph createBaseCaseEmptyString(); public NFAGraph createBaseCaseSymbol(String symbol); public NFAGraph unionNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph joinNFAs(NFAGraph m1, NFAGraph m2); public NFAGraph starNFA(NFAGraph m, RegexStarOperator starOperator); public NFAGraph plusNFA(NFAGraph m, RegexPlusOperator plusOperator); public NFAGraph countClosureNFA(NFAGraph m, RegexCountClosureOperator countClosureOperator);
public NFAGraph questionMarkNFA(NFAGraph m, RegexQuestionMarkOperator questionMarkOperator);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/regexcompiler/ParseTree.java
// Path: src/main/java/regexcompiler/RegexSubexpression.java // public enum SubexpressionType { // SYMBOL, // ESCAPED_SYMBOL, // CHARACTER_CLASS, // GROUP, // } // // Path: src/main/java/regexcompiler/RegexToken.java // public enum TokenType { // SUBEXPRESSION, // OPERATOR, // ANCHOR; // }
import java.util.Iterator; import java.util.LinkedList; import java.util.List; import regexcompiler.RegexSubexpression.SubexpressionType; import regexcompiler.RegexToken.TokenType;
@Override public String toString() { StringBuilder treeStringBuilder = new StringBuilder(); dfsTree(root, treeStringBuilder); return treeStringBuilder.toString(); } private void dfsTree(TreeNode currentNode, StringBuilder sb) { if (!currentNode.getChildren().isEmpty()) { sb.append(currentNode); sb.append(getBracketType(currentNode, true)); Iterator<TreeNode> childIterator = currentNode.getChildren().iterator(); while (childIterator.hasNext()) { TreeNode child = childIterator.next(); dfsTree(child, sb); if (childIterator.hasNext()) { sb.append(", "); } } sb.append(getBracketType(currentNode, false)); } else { sb.append("'" + currentNode + "'"); } } private String getBracketType(TreeNode node, boolean isOpen) { RegexToken token = node.getRegexToken();
// Path: src/main/java/regexcompiler/RegexSubexpression.java // public enum SubexpressionType { // SYMBOL, // ESCAPED_SYMBOL, // CHARACTER_CLASS, // GROUP, // } // // Path: src/main/java/regexcompiler/RegexToken.java // public enum TokenType { // SUBEXPRESSION, // OPERATOR, // ANCHOR; // } // Path: src/main/java/regexcompiler/ParseTree.java import java.util.Iterator; import java.util.LinkedList; import java.util.List; import regexcompiler.RegexSubexpression.SubexpressionType; import regexcompiler.RegexToken.TokenType; @Override public String toString() { StringBuilder treeStringBuilder = new StringBuilder(); dfsTree(root, treeStringBuilder); return treeStringBuilder.toString(); } private void dfsTree(TreeNode currentNode, StringBuilder sb) { if (!currentNode.getChildren().isEmpty()) { sb.append(currentNode); sb.append(getBracketType(currentNode, true)); Iterator<TreeNode> childIterator = currentNode.getChildren().iterator(); while (childIterator.hasNext()) { TreeNode child = childIterator.next(); dfsTree(child, sb); if (childIterator.hasNext()) { sb.append(", "); } } sb.append(getBracketType(currentNode, false)); } else { sb.append("'" + currentNode + "'"); } } private String getBracketType(TreeNode node, boolean isOpen) { RegexToken token = node.getRegexToken();
if (token.getTokenType() == TokenType.OPERATOR) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/regexcompiler/ParseTree.java
// Path: src/main/java/regexcompiler/RegexSubexpression.java // public enum SubexpressionType { // SYMBOL, // ESCAPED_SYMBOL, // CHARACTER_CLASS, // GROUP, // } // // Path: src/main/java/regexcompiler/RegexToken.java // public enum TokenType { // SUBEXPRESSION, // OPERATOR, // ANCHOR; // }
import java.util.Iterator; import java.util.LinkedList; import java.util.List; import regexcompiler.RegexSubexpression.SubexpressionType; import regexcompiler.RegexToken.TokenType;
public static class TreeNode { private List<TreeNode> children; public List<TreeNode> getChildren() { return children; } public void addChild(TreeNode child) { children.add(child); } private final RegexToken regexToken; public RegexToken getRegexToken() { return regexToken; } private int getRegexIndex() { return regexToken.getIndex(); } public TreeNode(RegexToken regexToken) { this.regexToken = regexToken; children = new LinkedList<TreeNode>(); } @Override public String toString() { if (regexToken.getTokenType() == TokenType.SUBEXPRESSION) { RegexSubexpression<?> subexpressionToken = (RegexSubexpression<?>) regexToken;
// Path: src/main/java/regexcompiler/RegexSubexpression.java // public enum SubexpressionType { // SYMBOL, // ESCAPED_SYMBOL, // CHARACTER_CLASS, // GROUP, // } // // Path: src/main/java/regexcompiler/RegexToken.java // public enum TokenType { // SUBEXPRESSION, // OPERATOR, // ANCHOR; // } // Path: src/main/java/regexcompiler/ParseTree.java import java.util.Iterator; import java.util.LinkedList; import java.util.List; import regexcompiler.RegexSubexpression.SubexpressionType; import regexcompiler.RegexToken.TokenType; public static class TreeNode { private List<TreeNode> children; public List<TreeNode> getChildren() { return children; } public void addChild(TreeNode child) { children.add(child); } private final RegexToken regexToken; public RegexToken getRegexToken() { return regexToken; } private int getRegexIndex() { return regexToken.getIndex(); } public TreeNode(RegexToken regexToken) { this.regexToken = regexToken; children = new LinkedList<TreeNode>(); } @Override public String toString() { if (regexToken.getTokenType() == TokenType.SUBEXPRESSION) { RegexSubexpression<?> subexpressionToken = (RegexSubexpression<?>) regexToken;
if (subexpressionToken.getSubexpressionType() == SubexpressionType.GROUP) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/PlusOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // }
import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType;
package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // Path: src/main/java/preprocessor/PlusOperatorExpansion.java import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override
protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/PlusOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // }
import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType;
package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // Path: src/main/java/preprocessor/PlusOperatorExpansion.java import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override
protected RegexOperator getOperator() {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/PlusOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // }
import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType;
package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override protected RegexOperator getOperator() {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // Path: src/main/java/preprocessor/PlusOperatorExpansion.java import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override protected RegexOperator getOperator() {
return new QuantifiableOperator("+", OperatorType.PLUS);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/PlusOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // }
import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType;
package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override protected RegexOperator getOperator() {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // Path: src/main/java/preprocessor/PlusOperatorExpansion.java import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; package preprocessor; public class PlusOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) { resultBuilder.append(factor.getRepresentation() + factor.getRepresentation() + "*"); } @Override protected RegexOperator getOperator() {
return new QuantifiableOperator("+", OperatorType.PLUS);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/DequantifierRule.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // }
import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType;
package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // Path: src/main/java/preprocessor/DequantifierRule.java import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override
public String process(List<RegexToken> tokenStream) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/DequantifierRule.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // }
import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType;
package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // Path: src/main/java/preprocessor/DequantifierRule.java import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) {
if (tokens[i].getTokenType() == TokenType.REGEX_OPERATOR) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/DequantifierRule.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // }
import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType;
package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_OPERATOR) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // Path: src/main/java/preprocessor/DequantifierRule.java import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_OPERATOR) {
RegexOperator operatorToken = (RegexOperator) tokens[i];
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/DequantifierRule.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // }
import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType;
package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_OPERATOR) { RegexOperator operatorToken = (RegexOperator) tokens[i]; if (operatorToken.getIsQuantifiable()) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class QuantifiableOperator extends RegexOperator { // // public enum Quantifier { // GREEDY, POSSESIVE, RELUCTANT // } // // private Quantifier quantifier; // public Quantifier getOperatorQuantifier() { // return quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType, Quantifier quantifier) { // super(operatorSequence, operatorType); // // this.quantifier = quantifier; // } // // public QuantifiableOperator(String operatorSequence, OperatorType operatorType) { // super(operatorSequence, operatorType); // // this.quantifier = Quantifier.GREEDY; // } // // @Override // public boolean getIsQuantifiable() { // return true; // } // // public void setOperatorQuantifier(Quantifier quantifier) { // this.quantifier = quantifier; // } // // @Override // public String toString() { // String q = ""; // switch (quantifier) { // case GREEDY: // q = "G"; // break; // case POSSESIVE: // q = "P"; // break; // case RELUCTANT: // q = "R"; // break; // } // return q + "QO( " + operatorSequence + " )"; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // Path: src/main/java/preprocessor/DequantifierRule.java import java.util.List; import preprocessor.ParsingPreprocessor.QuantifiableOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexToken; import preprocessor.ParsingPreprocessor.RegexToken.TokenType; package preprocessor; public class DequantifierRule implements PreprocessorRule { @Override public String process(List<RegexToken> tokenStream) { StringBuilder regexBuilder = new StringBuilder(); RegexToken tokens[] = new RegexToken[tokenStream.size()]; tokens = tokenStream.toArray(tokens); int numTokens = tokens.length; int i = 0; while (i < numTokens) { if (tokens[i].getTokenType() == TokenType.REGEX_OPERATOR) { RegexOperator operatorToken = (RegexOperator) tokens[i]; if (operatorToken.getIsQuantifiable()) {
QuantifiableOperator quantifiableOperator = (QuantifiableOperator) operatorToken;
NicolaasWeideman/RegexStaticAnalysis
src/main/java/nfa/NFAGraph.java
// Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public interface TransitionLabel { // // public static final int MIN_16UNICODE = 0; // public static final int MAX_16UNICODE = 65536; // // public static final int MIN_DIGIT = 48; // public static final int MAX_DIGIT = 57; // // public static final int MIN_SPACE = 9; // public static final int MAX_SPACE = 13; // // public static final int MIN_WORD1 = 65; // public static final int MAX_WORD1 = 90; // // public static final int MIN_WORD2 = 95; // public static final int MAX_WORD2 = 95; // // public static final int MIN_WORD3 = 97; // public static final int MAX_WORD3 = 122; // // public static final int HORIZONTAL_TAB = 9; // // public static final int VERTICAL_TAB = 11; // // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // // public TransitionType getTransitionType(); // // public abstract boolean matches(String word); // // public abstract boolean matches(TransitionLabel tl); // // public abstract TransitionLabel intersection(TransitionLabel tl); // // public abstract TransitionLabel union(TransitionLabel tl); // // public abstract TransitionLabel complement(); // // public abstract boolean isEmpty(); // // public abstract String getSymbol(); // // public abstract TransitionLabel copy(); // // public static void main(String [] args) { // @SuppressWarnings("unused") // Pattern p = Pattern.compile("\\p{ALPHA}"); // } // // } // // Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // }
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Iterator; import org.jgrapht.graph.DirectedPseudograph; import nfa.transitionlabel.TransitionLabel; import nfa.transitionlabel.TransitionLabel.TransitionType;
package nfa; /** * A graph representing an NFA. * * @author N. H. Weideman * */ public class NFAGraph extends DirectedPseudograph<NFAVertexND, NFAEdge> { private static final long serialVersionUID = 1L; /* The vertex representing the initial state of the NFA */ private NFAVertexND initialState; public NFAVertexND getInitialState() { return initialState; } public void setInitialState(NFAVertexND initialState) { if (!super.containsVertex(initialState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + initialState); } this.initialState = initialState; } /* The accepting states of the NFA */ private HashSet<NFAVertexND> acceptingStates; public void addAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + acceptingState); } acceptingStates.add(acceptingState); } public boolean isAcceptingState(String stateNumber) { return acceptingStates.contains(new NFAVertexND(stateNumber)); } public boolean isAcceptingState(NFAVertexND state) { return acceptingStates.contains(state); } public void removeAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contains accepting state: " + acceptingState); } acceptingStates.remove(acceptingState); } public Set<NFAVertexND> getAcceptingStates() { return acceptingStates; } public NFAGraph() { super(NFAEdge.class); acceptingStates = new HashSet<NFAVertexND>(); } /** * @return A new instance of a NFAGraph equal to this instance */ public NFAGraph copy() { NFAGraph c = new NFAGraph(); for (NFAVertexND v : super.vertexSet()) { c.addVertex(v.copy()); } for (NFAEdge e : super.edgeSet()) { c.addEdge(e.copy()); } if (initialState != null) { c.initialState = initialState.copy(); } for (NFAVertexND v : acceptingStates) { c.addAcceptingState(v.copy()); } return c; } /** * Adds a new edge to the NFA graph * * @param newEdge * The new edge to add * @return true if this graph did not already contain the specified edge */ public boolean addEdge(NFAEdge newEdge) { if (newEdge == null) { throw new NullPointerException("New edge cannot be null"); } if (newEdge.getTransitionLabel().isEmpty()) { return false; } NFAVertexND s = newEdge.getSourceVertex(); NFAVertexND t = newEdge.getTargetVertex(); if (super.containsEdge(newEdge)) { /* if the edge exists increase the number of its parallel edges */ NFAEdge e = getEdge(newEdge); e.incNumParallel(); } else if (newEdge.getIsEpsilonTransition()) { /* check if the NFA already has an epsilon transition between these states */ Set<NFAEdge> es = super.getAllEdges(s, t); for (NFAEdge currentEdge : es) { if (currentEdge.equals(newEdge)) { /* if it does, add the new edge as a parallel edge (priorities don't matter between the same states) */ currentEdge.incNumParallel(); return true; } } } else { /* check if the new edge overlaps the current edges */ Set<NFAEdge> es = super.getAllEdges(s, t); // TODO lightly tested for (NFAEdge currentEdge : es) { /* epsilon edges cannot overlap */
// Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public interface TransitionLabel { // // public static final int MIN_16UNICODE = 0; // public static final int MAX_16UNICODE = 65536; // // public static final int MIN_DIGIT = 48; // public static final int MAX_DIGIT = 57; // // public static final int MIN_SPACE = 9; // public static final int MAX_SPACE = 13; // // public static final int MIN_WORD1 = 65; // public static final int MAX_WORD1 = 90; // // public static final int MIN_WORD2 = 95; // public static final int MAX_WORD2 = 95; // // public static final int MIN_WORD3 = 97; // public static final int MAX_WORD3 = 122; // // public static final int HORIZONTAL_TAB = 9; // // public static final int VERTICAL_TAB = 11; // // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // // public TransitionType getTransitionType(); // // public abstract boolean matches(String word); // // public abstract boolean matches(TransitionLabel tl); // // public abstract TransitionLabel intersection(TransitionLabel tl); // // public abstract TransitionLabel union(TransitionLabel tl); // // public abstract TransitionLabel complement(); // // public abstract boolean isEmpty(); // // public abstract String getSymbol(); // // public abstract TransitionLabel copy(); // // public static void main(String [] args) { // @SuppressWarnings("unused") // Pattern p = Pattern.compile("\\p{ALPHA}"); // } // // } // // Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // Path: src/main/java/nfa/NFAGraph.java import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Iterator; import org.jgrapht.graph.DirectedPseudograph; import nfa.transitionlabel.TransitionLabel; import nfa.transitionlabel.TransitionLabel.TransitionType; package nfa; /** * A graph representing an NFA. * * @author N. H. Weideman * */ public class NFAGraph extends DirectedPseudograph<NFAVertexND, NFAEdge> { private static final long serialVersionUID = 1L; /* The vertex representing the initial state of the NFA */ private NFAVertexND initialState; public NFAVertexND getInitialState() { return initialState; } public void setInitialState(NFAVertexND initialState) { if (!super.containsVertex(initialState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + initialState); } this.initialState = initialState; } /* The accepting states of the NFA */ private HashSet<NFAVertexND> acceptingStates; public void addAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + acceptingState); } acceptingStates.add(acceptingState); } public boolean isAcceptingState(String stateNumber) { return acceptingStates.contains(new NFAVertexND(stateNumber)); } public boolean isAcceptingState(NFAVertexND state) { return acceptingStates.contains(state); } public void removeAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contains accepting state: " + acceptingState); } acceptingStates.remove(acceptingState); } public Set<NFAVertexND> getAcceptingStates() { return acceptingStates; } public NFAGraph() { super(NFAEdge.class); acceptingStates = new HashSet<NFAVertexND>(); } /** * @return A new instance of a NFAGraph equal to this instance */ public NFAGraph copy() { NFAGraph c = new NFAGraph(); for (NFAVertexND v : super.vertexSet()) { c.addVertex(v.copy()); } for (NFAEdge e : super.edgeSet()) { c.addEdge(e.copy()); } if (initialState != null) { c.initialState = initialState.copy(); } for (NFAVertexND v : acceptingStates) { c.addAcceptingState(v.copy()); } return c; } /** * Adds a new edge to the NFA graph * * @param newEdge * The new edge to add * @return true if this graph did not already contain the specified edge */ public boolean addEdge(NFAEdge newEdge) { if (newEdge == null) { throw new NullPointerException("New edge cannot be null"); } if (newEdge.getTransitionLabel().isEmpty()) { return false; } NFAVertexND s = newEdge.getSourceVertex(); NFAVertexND t = newEdge.getTargetVertex(); if (super.containsEdge(newEdge)) { /* if the edge exists increase the number of its parallel edges */ NFAEdge e = getEdge(newEdge); e.incNumParallel(); } else if (newEdge.getIsEpsilonTransition()) { /* check if the NFA already has an epsilon transition between these states */ Set<NFAEdge> es = super.getAllEdges(s, t); for (NFAEdge currentEdge : es) { if (currentEdge.equals(newEdge)) { /* if it does, add the new edge as a parallel edge (priorities don't matter between the same states) */ currentEdge.incNumParallel(); return true; } } } else { /* check if the new edge overlaps the current edges */ Set<NFAEdge> es = super.getAllEdges(s, t); // TODO lightly tested for (NFAEdge currentEdge : es) { /* epsilon edges cannot overlap */
if (currentEdge.getTransitionType() == TransitionType.SYMBOL) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/nfa/NFAGraph.java
// Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public interface TransitionLabel { // // public static final int MIN_16UNICODE = 0; // public static final int MAX_16UNICODE = 65536; // // public static final int MIN_DIGIT = 48; // public static final int MAX_DIGIT = 57; // // public static final int MIN_SPACE = 9; // public static final int MAX_SPACE = 13; // // public static final int MIN_WORD1 = 65; // public static final int MAX_WORD1 = 90; // // public static final int MIN_WORD2 = 95; // public static final int MAX_WORD2 = 95; // // public static final int MIN_WORD3 = 97; // public static final int MAX_WORD3 = 122; // // public static final int HORIZONTAL_TAB = 9; // // public static final int VERTICAL_TAB = 11; // // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // // public TransitionType getTransitionType(); // // public abstract boolean matches(String word); // // public abstract boolean matches(TransitionLabel tl); // // public abstract TransitionLabel intersection(TransitionLabel tl); // // public abstract TransitionLabel union(TransitionLabel tl); // // public abstract TransitionLabel complement(); // // public abstract boolean isEmpty(); // // public abstract String getSymbol(); // // public abstract TransitionLabel copy(); // // public static void main(String [] args) { // @SuppressWarnings("unused") // Pattern p = Pattern.compile("\\p{ALPHA}"); // } // // } // // Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // }
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Iterator; import org.jgrapht.graph.DirectedPseudograph; import nfa.transitionlabel.TransitionLabel; import nfa.transitionlabel.TransitionLabel.TransitionType;
package nfa; /** * A graph representing an NFA. * * @author N. H. Weideman * */ public class NFAGraph extends DirectedPseudograph<NFAVertexND, NFAEdge> { private static final long serialVersionUID = 1L; /* The vertex representing the initial state of the NFA */ private NFAVertexND initialState; public NFAVertexND getInitialState() { return initialState; } public void setInitialState(NFAVertexND initialState) { if (!super.containsVertex(initialState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + initialState); } this.initialState = initialState; } /* The accepting states of the NFA */ private HashSet<NFAVertexND> acceptingStates; public void addAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + acceptingState); } acceptingStates.add(acceptingState); } public boolean isAcceptingState(String stateNumber) { return acceptingStates.contains(new NFAVertexND(stateNumber)); } public boolean isAcceptingState(NFAVertexND state) { return acceptingStates.contains(state); } public void removeAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contains accepting state: " + acceptingState); } acceptingStates.remove(acceptingState); } public Set<NFAVertexND> getAcceptingStates() { return acceptingStates; } public NFAGraph() { super(NFAEdge.class); acceptingStates = new HashSet<NFAVertexND>(); } /** * @return A new instance of a NFAGraph equal to this instance */ public NFAGraph copy() { NFAGraph c = new NFAGraph(); for (NFAVertexND v : super.vertexSet()) { c.addVertex(v.copy()); } for (NFAEdge e : super.edgeSet()) { c.addEdge(e.copy()); } if (initialState != null) { c.initialState = initialState.copy(); } for (NFAVertexND v : acceptingStates) { c.addAcceptingState(v.copy()); } return c; } /** * Adds a new edge to the NFA graph * * @param newEdge * The new edge to add * @return true if this graph did not already contain the specified edge */ public boolean addEdge(NFAEdge newEdge) { if (newEdge == null) { throw new NullPointerException("New edge cannot be null"); } if (newEdge.getTransitionLabel().isEmpty()) { return false; } NFAVertexND s = newEdge.getSourceVertex(); NFAVertexND t = newEdge.getTargetVertex(); if (super.containsEdge(newEdge)) { /* if the edge exists increase the number of its parallel edges */ NFAEdge e = getEdge(newEdge); e.incNumParallel(); } else if (newEdge.getIsEpsilonTransition()) { /* check if the NFA already has an epsilon transition between these states */ Set<NFAEdge> es = super.getAllEdges(s, t); for (NFAEdge currentEdge : es) { if (currentEdge.equals(newEdge)) { /* if it does, add the new edge as a parallel edge (priorities don't matter between the same states) */ currentEdge.incNumParallel(); return true; } } } else { /* check if the new edge overlaps the current edges */ Set<NFAEdge> es = super.getAllEdges(s, t); // TODO lightly tested for (NFAEdge currentEdge : es) { /* epsilon edges cannot overlap */ if (currentEdge.getTransitionType() == TransitionType.SYMBOL) {
// Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public interface TransitionLabel { // // public static final int MIN_16UNICODE = 0; // public static final int MAX_16UNICODE = 65536; // // public static final int MIN_DIGIT = 48; // public static final int MAX_DIGIT = 57; // // public static final int MIN_SPACE = 9; // public static final int MAX_SPACE = 13; // // public static final int MIN_WORD1 = 65; // public static final int MAX_WORD1 = 90; // // public static final int MIN_WORD2 = 95; // public static final int MAX_WORD2 = 95; // // public static final int MIN_WORD3 = 97; // public static final int MAX_WORD3 = 122; // // public static final int HORIZONTAL_TAB = 9; // // public static final int VERTICAL_TAB = 11; // // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // // public TransitionType getTransitionType(); // // public abstract boolean matches(String word); // // public abstract boolean matches(TransitionLabel tl); // // public abstract TransitionLabel intersection(TransitionLabel tl); // // public abstract TransitionLabel union(TransitionLabel tl); // // public abstract TransitionLabel complement(); // // public abstract boolean isEmpty(); // // public abstract String getSymbol(); // // public abstract TransitionLabel copy(); // // public static void main(String [] args) { // @SuppressWarnings("unused") // Pattern p = Pattern.compile("\\p{ALPHA}"); // } // // } // // Path: src/main/java/nfa/transitionlabel/TransitionLabel.java // public enum TransitionType { // EPSILON, // SYMBOL, // OTHER // } // Path: src/main/java/nfa/NFAGraph.java import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Iterator; import org.jgrapht.graph.DirectedPseudograph; import nfa.transitionlabel.TransitionLabel; import nfa.transitionlabel.TransitionLabel.TransitionType; package nfa; /** * A graph representing an NFA. * * @author N. H. Weideman * */ public class NFAGraph extends DirectedPseudograph<NFAVertexND, NFAEdge> { private static final long serialVersionUID = 1L; /* The vertex representing the initial state of the NFA */ private NFAVertexND initialState; public NFAVertexND getInitialState() { return initialState; } public void setInitialState(NFAVertexND initialState) { if (!super.containsVertex(initialState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + initialState); } this.initialState = initialState; } /* The accepting states of the NFA */ private HashSet<NFAVertexND> acceptingStates; public void addAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contain vertex: " + acceptingState); } acceptingStates.add(acceptingState); } public boolean isAcceptingState(String stateNumber) { return acceptingStates.contains(new NFAVertexND(stateNumber)); } public boolean isAcceptingState(NFAVertexND state) { return acceptingStates.contains(state); } public void removeAcceptingState(NFAVertexND acceptingState) { if (!super.containsVertex(acceptingState)) { throw new IllegalArgumentException("Graph does not contains accepting state: " + acceptingState); } acceptingStates.remove(acceptingState); } public Set<NFAVertexND> getAcceptingStates() { return acceptingStates; } public NFAGraph() { super(NFAEdge.class); acceptingStates = new HashSet<NFAVertexND>(); } /** * @return A new instance of a NFAGraph equal to this instance */ public NFAGraph copy() { NFAGraph c = new NFAGraph(); for (NFAVertexND v : super.vertexSet()) { c.addVertex(v.copy()); } for (NFAEdge e : super.edgeSet()) { c.addEdge(e.copy()); } if (initialState != null) { c.initialState = initialState.copy(); } for (NFAVertexND v : acceptingStates) { c.addAcceptingState(v.copy()); } return c; } /** * Adds a new edge to the NFA graph * * @param newEdge * The new edge to add * @return true if this graph did not already contain the specified edge */ public boolean addEdge(NFAEdge newEdge) { if (newEdge == null) { throw new NullPointerException("New edge cannot be null"); } if (newEdge.getTransitionLabel().isEmpty()) { return false; } NFAVertexND s = newEdge.getSourceVertex(); NFAVertexND t = newEdge.getTargetVertex(); if (super.containsEdge(newEdge)) { /* if the edge exists increase the number of its parallel edges */ NFAEdge e = getEdge(newEdge); e.incNumParallel(); } else if (newEdge.getIsEpsilonTransition()) { /* check if the NFA already has an epsilon transition between these states */ Set<NFAEdge> es = super.getAllEdges(s, t); for (NFAEdge currentEdge : es) { if (currentEdge.equals(newEdge)) { /* if it does, add the new edge as a parallel edge (priorities don't matter between the same states) */ currentEdge.incNumParallel(); return true; } } } else { /* check if the new edge overlaps the current edges */ Set<NFAEdge> es = super.getAllEdges(s, t); // TODO lightly tested for (NFAEdge currentEdge : es) { /* epsilon edges cannot overlap */ if (currentEdge.getTransitionType() == TransitionType.SYMBOL) {
TransitionLabel tlCurrentEdge = currentEdge.getTransitionLabel();
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/ParsingPreprocessor.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum EscapeType { // CHARACTER, OCTAL, UNICODE, HEX, VERBATIM, CHARACTER_PROPERTY // }
import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import preprocessor.ParsingPreprocessor.CountClosureOperator.BoundsType; import preprocessor.ParsingPreprocessor.EscapeFactor.EscapeType;
if (level != 0) { groupBuilder.append(regexArr[i]); } escaped = false; i++; } String symbols = groupBuilder.toString(); RegexToken characterClassFactor = new CharacterClassFactor(symbols); tokenStream.add(characterClassFactor); break; case '\\': i++; if (i < regexArr.length && regexArr[i] == 'Q') { i++; while (true) { if (i < regexArr.length) { if (regexArr[i] == '\\') { i++; if (i < regexArr.length && regexArr[i] == 'E') { break; } else if (i < regexArr.length) { String currentSymbol = "" + regexArr[i]; RegexToken verbatimChar; if (canEscapeVerbatim(currentSymbol)) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum EscapeType { // CHARACTER, OCTAL, UNICODE, HEX, VERBATIM, CHARACTER_PROPERTY // } // Path: src/main/java/preprocessor/ParsingPreprocessor.java import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import preprocessor.ParsingPreprocessor.CountClosureOperator.BoundsType; import preprocessor.ParsingPreprocessor.EscapeFactor.EscapeType; if (level != 0) { groupBuilder.append(regexArr[i]); } escaped = false; i++; } String symbols = groupBuilder.toString(); RegexToken characterClassFactor = new CharacterClassFactor(symbols); tokenStream.add(characterClassFactor); break; case '\\': i++; if (i < regexArr.length && regexArr[i] == 'Q') { i++; while (true) { if (i < regexArr.length) { if (regexArr[i] == '\\') { i++; if (i < regexArr.length && regexArr[i] == 'E') { break; } else if (i < regexArr.length) { String currentSymbol = "" + regexArr[i]; RegexToken verbatimChar; if (canEscapeVerbatim(currentSymbol)) {
verbatimChar = new EscapeFactor("\\" + currentSymbol, EscapeType.VERBATIM);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/ParsingPreprocessor.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum EscapeType { // CHARACTER, OCTAL, UNICODE, HEX, VERBATIM, CHARACTER_PROPERTY // }
import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import preprocessor.ParsingPreprocessor.CountClosureOperator.BoundsType; import preprocessor.ParsingPreprocessor.EscapeFactor.EscapeType;
operatorSymbol = countedClosureBuilder.toString(); Pattern boundedPattern = Pattern.compile("\\{(\\d+),(\\d+)\\}"); Pattern unboundedPattern = Pattern.compile("\\{(\\d+),\\}"); Pattern constantRepititionPattern = Pattern.compile("\\{(\\d+)\\}"); Matcher boundedMatcher = boundedPattern.matcher(operatorSymbol); Matcher unboundedMatcher = unboundedPattern.matcher(operatorSymbol); Matcher constantRepititionMatcher = constantRepititionPattern.matcher(operatorSymbol); int low, high; if (boundedMatcher.find()) { String lowStr = boundedMatcher.group(1); low = Integer.parseInt(lowStr); String highStr = boundedMatcher.group(2); high = Integer.parseInt(highStr); if (high < low || low < 0 || high > MAX_REPETITION) { throw new PatternSyntaxException("Illegal repetition range", regex, i); } operatorToken = new CountClosureOperator(operatorSymbol, quantifier, low, high); tokenStream.add(operatorToken); } else if (unboundedMatcher.find()) { String lowStr = unboundedMatcher.group(1); low = Integer.parseInt(lowStr); if (low < 0 || low > MAX_REPETITION) { throw new PatternSyntaxException("Illegal repetition range", regex, i); }
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum EscapeType { // CHARACTER, OCTAL, UNICODE, HEX, VERBATIM, CHARACTER_PROPERTY // } // Path: src/main/java/preprocessor/ParsingPreprocessor.java import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import preprocessor.ParsingPreprocessor.CountClosureOperator.BoundsType; import preprocessor.ParsingPreprocessor.EscapeFactor.EscapeType; operatorSymbol = countedClosureBuilder.toString(); Pattern boundedPattern = Pattern.compile("\\{(\\d+),(\\d+)\\}"); Pattern unboundedPattern = Pattern.compile("\\{(\\d+),\\}"); Pattern constantRepititionPattern = Pattern.compile("\\{(\\d+)\\}"); Matcher boundedMatcher = boundedPattern.matcher(operatorSymbol); Matcher unboundedMatcher = unboundedPattern.matcher(operatorSymbol); Matcher constantRepititionMatcher = constantRepititionPattern.matcher(operatorSymbol); int low, high; if (boundedMatcher.find()) { String lowStr = boundedMatcher.group(1); low = Integer.parseInt(lowStr); String highStr = boundedMatcher.group(2); high = Integer.parseInt(highStr); if (high < low || low < 0 || high > MAX_REPETITION) { throw new PatternSyntaxException("Illegal repetition range", regex, i); } operatorToken = new CountClosureOperator(operatorSymbol, quantifier, low, high); tokenStream.add(operatorToken); } else if (unboundedMatcher.find()) { String lowStr = unboundedMatcher.group(1); low = Integer.parseInt(lowStr); if (low < 0 || low > MAX_REPETITION) { throw new PatternSyntaxException("Illegal repetition range", regex, i); }
operatorToken = new CountClosureOperator(operatorSymbol, quantifier, low, BoundsType.UNBOUNDED);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/matcher/driver/MatcherExploitStringTester.java
// Path: src/main/java/analysis/AnalysisSettings.java // public static enum NFAConstruction { // THOMPSON, // JAVA; // }
import matcher.*; import regexcompiler.*; import analysis.AnalysisSettings.NFAConstruction;
pumpSeparators[(i - 1) / 2] = makeVerbatim(args[i]); pumps[(i - 1) / 2] = makeVerbatim(args[i + 1]); } for (int i = 0; i < numPumps; i++) { System.out.println("ps_" + i + ": " + pumps[i] + " p_" + i + ": " + pumpSeparators[i]); } String suffix = makeVerbatim(args[args.length - 1]); int counter = 1; StringBuilder sb = new StringBuilder("Trying to exploit " + patternStr + " with "); for (int i = 1; i < args.length - 1; i += 2) { sb.append(args[i] + args[i + 1] + "..." + args[i + 1]); } sb.append(suffix); System.out.println(sb.toString()); StringBuilder[] pumpers = new StringBuilder[numPumps]; for (int i = 0; i < numPumps; i++) { pumpers[i] = new StringBuilder(pumps[i]); } while (true) { StringBuilder exploitStringBuilder = new StringBuilder(); for (int i = 0; i < numPumps; i++) { exploitStringBuilder.append(pumpSeparators[i]); exploitStringBuilder.append(pumpers[i].toString()); pumpers[i].append(pumps[i]); } exploitStringBuilder.append(suffix); String exploitString = exploitStringBuilder.toString(); //System.out.println(exploitString);
// Path: src/main/java/analysis/AnalysisSettings.java // public static enum NFAConstruction { // THOMPSON, // JAVA; // } // Path: src/main/java/matcher/driver/MatcherExploitStringTester.java import matcher.*; import regexcompiler.*; import analysis.AnalysisSettings.NFAConstruction; pumpSeparators[(i - 1) / 2] = makeVerbatim(args[i]); pumps[(i - 1) / 2] = makeVerbatim(args[i + 1]); } for (int i = 0; i < numPumps; i++) { System.out.println("ps_" + i + ": " + pumps[i] + " p_" + i + ": " + pumpSeparators[i]); } String suffix = makeVerbatim(args[args.length - 1]); int counter = 1; StringBuilder sb = new StringBuilder("Trying to exploit " + patternStr + " with "); for (int i = 1; i < args.length - 1; i += 2) { sb.append(args[i] + args[i + 1] + "..." + args[i + 1]); } sb.append(suffix); System.out.println(sb.toString()); StringBuilder[] pumpers = new StringBuilder[numPumps]; for (int i = 0; i < numPumps; i++) { pumpers[i] = new StringBuilder(pumps[i]); } while (true) { StringBuilder exploitStringBuilder = new StringBuilder(); for (int i = 0; i < numPumps; i++) { exploitStringBuilder.append(pumpSeparators[i]); exploitStringBuilder.append(pumpers[i].toString()); pumpers[i].append(pumps[i]); } exploitStringBuilder.append(suffix); String exploitString = exploitStringBuilder.toString(); //System.out.println(exploitString);
MyPattern pattern = MyPattern.compile(patternStr, NFAConstruction.JAVA);
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/CountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class CountClosureOperatorExpansion extends OperatorExpansionRule { @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/CountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class CountClosureOperatorExpansion extends OperatorExpansionRule { @Override
protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/CountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
package preprocessor; public class CountClosureOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/CountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; package preprocessor; public class CountClosureOperatorExpansion extends OperatorExpansionRule { @Override protected void expandOperator(StringBuilder resultBuilder, RegexToken factor, RegexToken operator) {
CountClosureOperator cco = (CountClosureOperator) operator;
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/CountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
} expansionBuilder.append(")"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandUnbounded(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(factor.getRepresentation() + "*"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandConstantRepitition(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/CountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; } expansionBuilder.append(")"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandUnbounded(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(factor.getRepresentation() + "*"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandConstantRepitition(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } @Override
protected RegexOperator getOperator() {
NicolaasWeideman/RegexStaticAnalysis
src/main/java/preprocessor/CountClosureOperatorExpansion.java
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // }
import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken;
resultBuilder.append(expansionBuilder); } private void expandUnbounded(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(factor.getRepresentation() + "*"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandConstantRepitition(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } @Override protected RegexOperator getOperator() { throw new UnsupportedOperationException(); } @Override
// Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class CountClosureOperator extends QuantifiableOperator { // // public enum BoundsType { // BOUNDED, UNBOUNDED, CONSTANT_REPETITION // } // // private final int low; // public int getLow() { // return low; // } // // private final int high; // public int getHigh() { // return high; // } // // private final BoundsType boundsType; // public BoundsType getBoundsType() { // return boundsType; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, int high) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // this.high = high; // // this.boundsType = BoundsType.BOUNDED; // } // // public CountClosureOperator(String operatorSequence, Quantifier quantifier, int low, BoundsType boundsType) { // super(operatorSequence, OperatorType.COUNT, quantifier); // this.low = low; // // switch (boundsType) { // case UNBOUNDED: // high = Integer.MAX_VALUE; // break; // case CONSTANT_REPETITION: // high = low; // break; // default: // throw new IllegalArgumentException("Upper bounds needs to be specified."); // } // this.boundsType = boundsType; // } // // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static class RegexOperator implements RegexToken { // // protected final String operatorSequence; // // public String getOperator() { // return operatorSequence; // } // // public RegexOperator(String operatorSequence, OperatorType operatorType) { // this.operatorSequence = operatorSequence; // this.operatorType = operatorType; // } // // public boolean getIsQuantifiable() { // return false; // } // // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // private final OperatorType operatorType; // public OperatorType getOperatorType() { // return operatorType; // } // // @Override // public TokenType getTokenType() { // return TokenType.REGEX_OPERATOR; // } // // @Override // public String toString() { // return "O( " + operatorSequence + " )"; // } // // @Override // public String getRepresentation() { // return operatorSequence; // } // // @Override // public boolean equals(Object o) { // if (o == null) { // return false; // } // // if (o == this) { // return true; // } // // if (!(o instanceof RegexOperator)) { // return false; // } // // RegexOperator ro = (RegexOperator) o; // return ro.operatorSequence.equals(operatorSequence); // } // // @Override // public int hashCode() { // return operatorSequence.hashCode(); // } // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // public enum OperatorType { // PLUS, STAR, QM, COUNT, OR // } // // Path: src/main/java/preprocessor/ParsingPreprocessor.java // static interface RegexToken { // // public enum TokenType { // REGEX_FACTOR, REGEX_OPERATOR // } // // public TokenType getTokenType(); // // public String getRepresentation(); // // } // Path: src/main/java/preprocessor/CountClosureOperatorExpansion.java import preprocessor.ParsingPreprocessor.CountClosureOperator; import preprocessor.ParsingPreprocessor.RegexOperator; import preprocessor.ParsingPreprocessor.RegexOperator.OperatorType; import preprocessor.ParsingPreprocessor.RegexToken; resultBuilder.append(expansionBuilder); } private void expandUnbounded(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(factor.getRepresentation() + "*"); expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } private void expandConstantRepitition(StringBuilder resultBuilder, RegexToken factor, CountClosureOperator cco) { int low = cco.getLow(); StringBuilder expansionBuilder = new StringBuilder("("); for (int i = 0; i < low; i++) { expansionBuilder.append(factor.getRepresentation()); } expansionBuilder.append(")"); resultBuilder.append(expansionBuilder); } @Override protected RegexOperator getOperator() { throw new UnsupportedOperationException(); } @Override
protected OperatorType getOperatorType() {
utnfrrojava/java2016
ejemplos-clase/JavaCraftWeb/src/servlets/start.java
// Path: ejercicios/Ej05ABMCSimplePersonas/src/entidades/Persona.java // public class Persona { // private int id; // private int dni; // private String nombre; // private String apellido; // private boolean habilitado; // // // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public int getDni() { // return dni; // } // public void setDni(int dni) { // this.dni = dni; // } // public String getNombre() { // return nombre; // } // public void setNombre(String nombre) { // this.nombre = nombre; // }public Persona(){ // // } // public String getApellido() { // return apellido; // } // public void setApellido(String apellido) { // this.apellido = apellido; // } // public boolean isHabilitado() { // return habilitado; // } // public void setHabilitado(boolean habilitado) { // this.habilitado = habilitado; // } // // @Override // public boolean equals(Object per){ // return per instanceof Persona && ((Persona)per).getDni() == this.getDni(); // } // // } // // Path: ejercicios/Ej05ABMCSimplePersonas/src/negocio/CtrlABMCPersona.java // public class CtrlABMCPersona { // // private ArrayList<Persona> personas; // // private data.DataPersona dataPer; // // // public CtrlABMCPersona(){ // personas = new ArrayList<Persona>(); // dataPer=new DataPersona(); // } // // public void add(Persona p) throws ApplicationException { // dataPer.add(p); // // /*if(!personas.contains(p)){ // personas.add(p); // } else { // throw new ApplicationException("La persona ya existe"); // }*/ // } // // public void update(Persona p) throws ApplicationException{ // /*if(personas.contains(p)){ // Persona perEnc=this.getPersona(p); // perEnc.setApellido(p.getApellido()); // perEnc.setNombre(p.getNombre()); // perEnc.setHabilitado(p.isHabilitado()); // //int a=0; // //int b=a/a; // }else{ // throw new ApplicationException("La persona no existe"); // }*/ // // dataPer.update(p); // } // // public void delete(Persona p){ // dataPer.delete(p);; // } // // public Persona getPersona(Persona p){ // /*Persona perEnc=null; // int i=personas.indexOf(p); // if(i>=0){ // perEnc=personas.get(i); // } // return perEnc;*/ // return dataPer.getByDni(p); // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entidades.Persona; import negocio.CtrlABMCPersona;
package servlets; /** * Servlet implementation class start */ @WebServlet("/start") public class start extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public start() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: ejercicios/Ej05ABMCSimplePersonas/src/entidades/Persona.java // public class Persona { // private int id; // private int dni; // private String nombre; // private String apellido; // private boolean habilitado; // // // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public int getDni() { // return dni; // } // public void setDni(int dni) { // this.dni = dni; // } // public String getNombre() { // return nombre; // } // public void setNombre(String nombre) { // this.nombre = nombre; // }public Persona(){ // // } // public String getApellido() { // return apellido; // } // public void setApellido(String apellido) { // this.apellido = apellido; // } // public boolean isHabilitado() { // return habilitado; // } // public void setHabilitado(boolean habilitado) { // this.habilitado = habilitado; // } // // @Override // public boolean equals(Object per){ // return per instanceof Persona && ((Persona)per).getDni() == this.getDni(); // } // // } // // Path: ejercicios/Ej05ABMCSimplePersonas/src/negocio/CtrlABMCPersona.java // public class CtrlABMCPersona { // // private ArrayList<Persona> personas; // // private data.DataPersona dataPer; // // // public CtrlABMCPersona(){ // personas = new ArrayList<Persona>(); // dataPer=new DataPersona(); // } // // public void add(Persona p) throws ApplicationException { // dataPer.add(p); // // /*if(!personas.contains(p)){ // personas.add(p); // } else { // throw new ApplicationException("La persona ya existe"); // }*/ // } // // public void update(Persona p) throws ApplicationException{ // /*if(personas.contains(p)){ // Persona perEnc=this.getPersona(p); // perEnc.setApellido(p.getApellido()); // perEnc.setNombre(p.getNombre()); // perEnc.setHabilitado(p.isHabilitado()); // //int a=0; // //int b=a/a; // }else{ // throw new ApplicationException("La persona no existe"); // }*/ // // dataPer.update(p); // } // // public void delete(Persona p){ // dataPer.delete(p);; // } // // public Persona getPersona(Persona p){ // /*Persona perEnc=null; // int i=personas.indexOf(p); // if(i>=0){ // perEnc=personas.get(i); // } // return perEnc;*/ // return dataPer.getByDni(p); // } // } // Path: ejemplos-clase/JavaCraftWeb/src/servlets/start.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entidades.Persona; import negocio.CtrlABMCPersona; package servlets; /** * Servlet implementation class start */ @WebServlet("/start") public class start extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public start() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CtrlABMCPersona ctrl = new CtrlABMCPersona();
utnfrrojava/java2016
ejemplos-clase/JavaCraftWeb/src/servlets/start.java
// Path: ejercicios/Ej05ABMCSimplePersonas/src/entidades/Persona.java // public class Persona { // private int id; // private int dni; // private String nombre; // private String apellido; // private boolean habilitado; // // // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public int getDni() { // return dni; // } // public void setDni(int dni) { // this.dni = dni; // } // public String getNombre() { // return nombre; // } // public void setNombre(String nombre) { // this.nombre = nombre; // }public Persona(){ // // } // public String getApellido() { // return apellido; // } // public void setApellido(String apellido) { // this.apellido = apellido; // } // public boolean isHabilitado() { // return habilitado; // } // public void setHabilitado(boolean habilitado) { // this.habilitado = habilitado; // } // // @Override // public boolean equals(Object per){ // return per instanceof Persona && ((Persona)per).getDni() == this.getDni(); // } // // } // // Path: ejercicios/Ej05ABMCSimplePersonas/src/negocio/CtrlABMCPersona.java // public class CtrlABMCPersona { // // private ArrayList<Persona> personas; // // private data.DataPersona dataPer; // // // public CtrlABMCPersona(){ // personas = new ArrayList<Persona>(); // dataPer=new DataPersona(); // } // // public void add(Persona p) throws ApplicationException { // dataPer.add(p); // // /*if(!personas.contains(p)){ // personas.add(p); // } else { // throw new ApplicationException("La persona ya existe"); // }*/ // } // // public void update(Persona p) throws ApplicationException{ // /*if(personas.contains(p)){ // Persona perEnc=this.getPersona(p); // perEnc.setApellido(p.getApellido()); // perEnc.setNombre(p.getNombre()); // perEnc.setHabilitado(p.isHabilitado()); // //int a=0; // //int b=a/a; // }else{ // throw new ApplicationException("La persona no existe"); // }*/ // // dataPer.update(p); // } // // public void delete(Persona p){ // dataPer.delete(p);; // } // // public Persona getPersona(Persona p){ // /*Persona perEnc=null; // int i=personas.indexOf(p); // if(i>=0){ // perEnc=personas.get(i); // } // return perEnc;*/ // return dataPer.getByDni(p); // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entidades.Persona; import negocio.CtrlABMCPersona;
package servlets; /** * Servlet implementation class start */ @WebServlet("/start") public class start extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public start() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CtrlABMCPersona ctrl = new CtrlABMCPersona();
// Path: ejercicios/Ej05ABMCSimplePersonas/src/entidades/Persona.java // public class Persona { // private int id; // private int dni; // private String nombre; // private String apellido; // private boolean habilitado; // // // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public int getDni() { // return dni; // } // public void setDni(int dni) { // this.dni = dni; // } // public String getNombre() { // return nombre; // } // public void setNombre(String nombre) { // this.nombre = nombre; // }public Persona(){ // // } // public String getApellido() { // return apellido; // } // public void setApellido(String apellido) { // this.apellido = apellido; // } // public boolean isHabilitado() { // return habilitado; // } // public void setHabilitado(boolean habilitado) { // this.habilitado = habilitado; // } // // @Override // public boolean equals(Object per){ // return per instanceof Persona && ((Persona)per).getDni() == this.getDni(); // } // // } // // Path: ejercicios/Ej05ABMCSimplePersonas/src/negocio/CtrlABMCPersona.java // public class CtrlABMCPersona { // // private ArrayList<Persona> personas; // // private data.DataPersona dataPer; // // // public CtrlABMCPersona(){ // personas = new ArrayList<Persona>(); // dataPer=new DataPersona(); // } // // public void add(Persona p) throws ApplicationException { // dataPer.add(p); // // /*if(!personas.contains(p)){ // personas.add(p); // } else { // throw new ApplicationException("La persona ya existe"); // }*/ // } // // public void update(Persona p) throws ApplicationException{ // /*if(personas.contains(p)){ // Persona perEnc=this.getPersona(p); // perEnc.setApellido(p.getApellido()); // perEnc.setNombre(p.getNombre()); // perEnc.setHabilitado(p.isHabilitado()); // //int a=0; // //int b=a/a; // }else{ // throw new ApplicationException("La persona no existe"); // }*/ // // dataPer.update(p); // } // // public void delete(Persona p){ // dataPer.delete(p);; // } // // public Persona getPersona(Persona p){ // /*Persona perEnc=null; // int i=personas.indexOf(p); // if(i>=0){ // perEnc=personas.get(i); // } // return perEnc;*/ // return dataPer.getByDni(p); // } // } // Path: ejemplos-clase/JavaCraftWeb/src/servlets/start.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entidades.Persona; import negocio.CtrlABMCPersona; package servlets; /** * Servlet implementation class start */ @WebServlet("/start") public class start extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public start() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CtrlABMCPersona ctrl = new CtrlABMCPersona();
Persona p1= new Persona();
alt236/EasyCursor---Android
library/src/test/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryBuilderTest.java
// Path: library/src/main/java/uk/co/alt236/easycursor/EasyQueryModel.java // public interface EasyQueryModel extends QueryModelInfo { // // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Sets a comment on the model // * // * @param comment the comment to save // */ // void setModelComment(String comment); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Sets a tag on the model // * // * @param tag the tag to save // */ // void setModelTag(String tag); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // // /** // * Sets the model version // * // * @param version the version to save // */ // void setModelVersion(int version); // // /** // * Will return the JSON representation of this QueryModel. // * // * @return the resulting JSON String // * @throws JSONException if there was an error creating the JSON // */ // String toJson() throws JSONException; // }
import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Arrays; import uk.co.alt236.easycursor.EasyQueryModel; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
final String sql = "RAW_SQL"; final String[] args = {"a", "b"}; final RawQueryModel model = (RawQueryModel) new SqlQueryModel.RawQueryBuilder() .setModelComment(comment) .setModelTag(tag) .setModelVersion(version) .setSelectionArgs(args) .setRawSql(sql) .build(); final String json = model.toJson(); final RawQueryModel model2 = (RawQueryModel) SqlJsonModelConverter.convert(json); assertEquals(model.getModelComment(), model2.getModelComment()); assertEquals(model.getModelTag(), model2.getModelTag()); assertEquals(model.getModelVersion(), model2.getModelVersion()); assertTrue(Arrays.equals(model.getSelectionArgs(), model2.getSelectionArgs())); assertEquals(model.getRawSql(), model2.getRawSql()); } @Test public void testModelInfo() throws Exception { final String comment = "comment"; final String tag = "tag"; final int version = 22; final String sql = "RAW_SQL"; final String[] args = {"a", "b"};
// Path: library/src/main/java/uk/co/alt236/easycursor/EasyQueryModel.java // public interface EasyQueryModel extends QueryModelInfo { // // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Sets a comment on the model // * // * @param comment the comment to save // */ // void setModelComment(String comment); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Sets a tag on the model // * // * @param tag the tag to save // */ // void setModelTag(String tag); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // // /** // * Sets the model version // * // * @param version the version to save // */ // void setModelVersion(int version); // // /** // * Will return the JSON representation of this QueryModel. // * // * @return the resulting JSON String // * @throws JSONException if there was an error creating the JSON // */ // String toJson() throws JSONException; // } // Path: library/src/test/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryBuilderTest.java import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Arrays; import uk.co.alt236.easycursor.EasyQueryModel; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; final String sql = "RAW_SQL"; final String[] args = {"a", "b"}; final RawQueryModel model = (RawQueryModel) new SqlQueryModel.RawQueryBuilder() .setModelComment(comment) .setModelTag(tag) .setModelVersion(version) .setSelectionArgs(args) .setRawSql(sql) .build(); final String json = model.toJson(); final RawQueryModel model2 = (RawQueryModel) SqlJsonModelConverter.convert(json); assertEquals(model.getModelComment(), model2.getModelComment()); assertEquals(model.getModelTag(), model2.getModelTag()); assertEquals(model.getModelVersion(), model2.getModelVersion()); assertTrue(Arrays.equals(model.getSelectionArgs(), model2.getSelectionArgs())); assertEquals(model.getRawSql(), model2.getRawSql()); } @Test public void testModelInfo() throws Exception { final String comment = "comment"; final String tag = "tag"; final int version = 22; final String sql = "RAW_SQL"; final String[] args = {"a", "b"};
final EasyQueryModel model = new SqlQueryModel.RawQueryBuilder()
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverter.java
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // }
import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.internal.conversion; public final class ObjectConverter { private static final int INT_BYTE_SIZE = 4; private static final int LONG_BYTE_SIZE = 8; private static final int FLOAT_BYTE_SIZE = 4; private static final int DOUBLE_BYTE_SIZE = 8; private static final int SHORT_BYTE_SIZE = 2; private static final String UTF_8 = "UTF-8"; private final String mEncoding; private final ByteOrder mByteOrder; public ObjectConverter() { this(UTF_8, ByteOrder.BIG_ENDIAN); } public ObjectConverter(final String encoding, final ByteOrder byteOrder) { mEncoding = encoding; mByteOrder = byteOrder; } private ByteBuffer getByteBuffer(final int size) { return ByteBuffer.allocate(size).order(mByteOrder); } private byte[] getBytes(final String string) { try { return string.getBytes(mEncoding); } catch (final UnsupportedEncodingException e) {
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverter.java import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.internal.conversion; public final class ObjectConverter { private static final int INT_BYTE_SIZE = 4; private static final int LONG_BYTE_SIZE = 8; private static final int FLOAT_BYTE_SIZE = 4; private static final int DOUBLE_BYTE_SIZE = 8; private static final int SHORT_BYTE_SIZE = 2; private static final String UTF_8 = "UTF-8"; private final String mEncoding; private final ByteOrder mByteOrder; public ObjectConverter() { this(UTF_8, ByteOrder.BIG_ENDIAN); } public ObjectConverter(final String encoding, final ByteOrder byteOrder) { mEncoding = encoding; mByteOrder = byteOrder; } private ByteBuffer getByteBuffer(final int size) { return ByteBuffer.allocate(size).order(mByteOrder); } private byte[] getBytes(final String string) { try { return string.getBytes(mEncoding); } catch (final UnsupportedEncodingException e) {
throw new ConversionErrorException(e);
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class SelectQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_MANAGED; private static final String FIELD_DISTINCT = "distinct"; private static final String FIELD_GROUP_BY = "groupBy"; private static final String FIELD_HAVING = "having"; private static final String FIELD_LIMIT = "limit"; private static final String FIELD_PROJECTION_IN = "projectionIn"; private static final String FIELD_SELECTION = "selection"; private static final String FIELD_SORT_ORDER = "sortOrder"; private static final String FIELD_STRICT = "strict"; private static final String FIELD_TABLES = "tables"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; private final boolean mDistinct; private final boolean mStrict; private final String mTables; private final String[] mProjectionIn; private final String[] mSelectionArgs; private final String mSelection; private final String mGroupBy; private final String mHaving; private final String mSortOrder; private final String mLimit;
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class SelectQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_MANAGED; private static final String FIELD_DISTINCT = "distinct"; private static final String FIELD_GROUP_BY = "groupBy"; private static final String FIELD_HAVING = "having"; private static final String FIELD_LIMIT = "limit"; private static final String FIELD_PROJECTION_IN = "projectionIn"; private static final String FIELD_SELECTION = "selection"; private static final String FIELD_SORT_ORDER = "sortOrder"; private static final String FIELD_STRICT = "strict"; private static final String FIELD_TABLES = "tables"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; private final boolean mDistinct; private final boolean mStrict; private final String mTables; private final String[] mProjectionIn; private final String[] mSelectionArgs; private final String mSelection; private final String mGroupBy; private final String mHaving; private final String mSortOrder; private final String mLimit;
public SelectQueryModel(final SqlSelectBuilder builder) {
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class SelectQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_MANAGED; private static final String FIELD_DISTINCT = "distinct"; private static final String FIELD_GROUP_BY = "groupBy"; private static final String FIELD_HAVING = "having"; private static final String FIELD_LIMIT = "limit"; private static final String FIELD_PROJECTION_IN = "projectionIn"; private static final String FIELD_SELECTION = "selection"; private static final String FIELD_SORT_ORDER = "sortOrder"; private static final String FIELD_STRICT = "strict"; private static final String FIELD_TABLES = "tables"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; private final boolean mDistinct; private final boolean mStrict; private final String mTables; private final String[] mProjectionIn; private final String[] mSelectionArgs; private final String mSelection; private final String mGroupBy; private final String mHaving; private final String mSortOrder; private final String mLimit; public SelectQueryModel(final SqlSelectBuilder builder) {
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class SelectQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_MANAGED; private static final String FIELD_DISTINCT = "distinct"; private static final String FIELD_GROUP_BY = "groupBy"; private static final String FIELD_HAVING = "having"; private static final String FIELD_LIMIT = "limit"; private static final String FIELD_PROJECTION_IN = "projectionIn"; private static final String FIELD_SELECTION = "selection"; private static final String FIELD_SORT_ORDER = "sortOrder"; private static final String FIELD_STRICT = "strict"; private static final String FIELD_TABLES = "tables"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; private final boolean mDistinct; private final boolean mStrict; private final String mTables; private final String[] mProjectionIn; private final String[] mSelectionArgs; private final String mSelection; private final String mGroupBy; private final String mHaving; private final String mSortOrder; private final String mLimit; public SelectQueryModel(final SqlSelectBuilder builder) {
super(builder instanceof QueryModelInfo ? (QueryModelInfo) builder : null,
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo;
* @return the Tables clause */ public String getTables() { return mTables; } /** * Returns whether or not this query is set to be Distinct. * * @return the Distinct setting */ public boolean isDistinct() { return mDistinct; } /** * Returns whether or not this query is set to be Strict. * This value is ignored if you are on a device running API lower than 14. * * @return the Strict setting */ public boolean isStrict() { return mStrict; } @Override public String toJson() throws JSONException { final JSONObject payload = new JSONObject(); addCommonFields(payload);
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlSelectBuilder.java // public interface SqlSelectBuilder { // // EasyQueryModel build(); // // String getGroupBy(); // // String getHaving(); // // String getLimit(); // // String[] getProjectionIn(); // // String getSelection(); // // String[] getSelectionArgs(); // // String getSortOrder(); // // String getTables(); // // boolean isDistinct(); // // boolean isStrict(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryModel.java import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlSelectBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; * @return the Tables clause */ public String getTables() { return mTables; } /** * Returns whether or not this query is set to be Distinct. * * @return the Distinct setting */ public boolean isDistinct() { return mDistinct; } /** * Returns whether or not this query is set to be Strict. * This value is ignored if you are on a device running API lower than 14. * * @return the Strict setting */ public boolean isStrict() { return mStrict; } @Override public String toJson() throws JSONException { final JSONObject payload = new JSONObject(); addCommonFields(payload);
JsonPayloadHelper.add(payload, FIELD_DISTINCT, mDistinct);
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/JsonWrapper.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import uk.co.alt236.easycursor.util.JsonPayloadHelper; import org.json.JSONObject; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class JsonWrapper implements QueryModelInfo { private final JSONObject mJsonObject; public JsonWrapper(final JSONObject jsonObject) { mJsonObject = jsonObject; } public boolean getBoolean(final String field) {
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/JsonWrapper.java import uk.co.alt236.easycursor.util.JsonPayloadHelper; import org.json.JSONObject; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class JsonWrapper implements QueryModelInfo { private final JSONObject mJsonObject; public JsonWrapper(final JSONObject jsonObject) { mJsonObject = jsonObject; } public boolean getBoolean(final String field) {
return JsonPayloadHelper.getBoolean(mJsonObject, field);
alt236/EasyCursor---Android
library/src/test/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryBuilderTest.java
// Path: library/src/main/java/uk/co/alt236/easycursor/EasyQueryModel.java // public interface EasyQueryModel extends QueryModelInfo { // // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Sets a comment on the model // * // * @param comment the comment to save // */ // void setModelComment(String comment); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Sets a tag on the model // * // * @param tag the tag to save // */ // void setModelTag(String tag); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // // /** // * Sets the model version // * // * @param version the version to save // */ // void setModelVersion(int version); // // /** // * Will return the JSON representation of this QueryModel. // * // * @return the resulting JSON String // * @throws JSONException if there was an error creating the JSON // */ // String toJson() throws JSONException; // }
import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Arrays; import uk.co.alt236.easycursor.EasyQueryModel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
.setProjectionIn(projectionIn) .setSortOrder("sortorder") .setStrict(true) .setTables("tables") .setSelection("selection") .setSelectionArgs(selectionArgs) .build(); final String json = model.toJson(); final SelectQueryModel model2 = (SelectQueryModel) SqlJsonModelConverter.convert(json); assertEquals(model.isDistinct(), model2.isDistinct()); assertEquals(model.getGroupBy(), model2.getGroupBy()); assertEquals(model.getHaving(), model2.getHaving()); assertEquals(model.getLimit(), model2.getLimit()); assertTrue(Arrays.equals(model.getProjectionIn(), model2.getProjectionIn())); assertEquals(model.getSortOrder(), model2.getSortOrder()); assertEquals(model.isStrict(), model2.isStrict()); assertEquals(model.getTables(), model2.getTables()); assertEquals(model.getSelection(), model2.getSelection()); assertTrue(Arrays.equals(model.getSelectionArgs(), model2.getSelectionArgs())); } @Test public void testModelInfo() { final String comment = "comment"; final String tag = "tag"; final int version = 22; final String[] args = {"a", "b"};
// Path: library/src/main/java/uk/co/alt236/easycursor/EasyQueryModel.java // public interface EasyQueryModel extends QueryModelInfo { // // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Sets a comment on the model // * // * @param comment the comment to save // */ // void setModelComment(String comment); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Sets a tag on the model // * // * @param tag the tag to save // */ // void setModelTag(String tag); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // // /** // * Sets the model version // * // * @param version the version to save // */ // void setModelVersion(int version); // // /** // * Will return the JSON representation of this QueryModel. // * // * @return the resulting JSON String // * @throws JSONException if there was an error creating the JSON // */ // String toJson() throws JSONException; // } // Path: library/src/test/java/uk/co/alt236/easycursor/sqlcursor/querymodels/SelectQueryBuilderTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Arrays; import uk.co.alt236.easycursor.EasyQueryModel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; .setProjectionIn(projectionIn) .setSortOrder("sortorder") .setStrict(true) .setTables("tables") .setSelection("selection") .setSelectionArgs(selectionArgs) .build(); final String json = model.toJson(); final SelectQueryModel model2 = (SelectQueryModel) SqlJsonModelConverter.convert(json); assertEquals(model.isDistinct(), model2.isDistinct()); assertEquals(model.getGroupBy(), model2.getGroupBy()); assertEquals(model.getHaving(), model2.getHaving()); assertEquals(model.getLimit(), model2.getLimit()); assertTrue(Arrays.equals(model.getProjectionIn(), model2.getProjectionIn())); assertEquals(model.getSortOrder(), model2.getSortOrder()); assertEquals(model.isStrict(), model2.isStrict()); assertEquals(model.getTables(), model2.getTables()); assertEquals(model.getSelection(), model2.getSelection()); assertTrue(Arrays.equals(model.getSelectionArgs(), model2.getSelectionArgs())); } @Test public void testModelInfo() { final String comment = "comment"; final String tag = "tag"; final int version = 22; final String[] args = {"a", "b"};
final EasyQueryModel model = new SqlQueryModel.SelectQueryBuilder()
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class RawQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_RAW; private static final String FIELD_RAW_SQL = "rawSql"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; // // Raw Query // private final String mRawSql; private final String[] mSelectionArgs;
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class RawQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_RAW; private static final String FIELD_RAW_SQL = "rawSql"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; // // Raw Query // private final String mRawSql; private final String[] mSelectionArgs;
public RawQueryModel(final SqlRawQueryBuilder builder) {
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper;
/* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class RawQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_RAW; private static final String FIELD_RAW_SQL = "rawSql"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; // // Raw Query // private final String mRawSql; private final String[] mSelectionArgs; public RawQueryModel(final SqlRawQueryBuilder builder) {
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; /* * *************************************************************************** * Copyright 2015 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.querymodels; /** * */ public class RawQueryModel extends SqlQueryModel { private static final int QUERY_TYPE = RawQueryModel.QUERY_TYPE_RAW; private static final String FIELD_RAW_SQL = "rawSql"; private static final String FIELD_SELECTION_ARGS = "selectionArgs"; // // Raw Query // private final String mRawSql; private final String[] mSelectionArgs; public RawQueryModel(final SqlRawQueryBuilder builder) {
super(builder instanceof QueryModelInfo ? (QueryModelInfo) builder : null,
alt236/EasyCursor---Android
library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper;
public RawQueryModel(final SqlRawQueryBuilder builder) { super(builder instanceof QueryModelInfo ? (QueryModelInfo) builder : null, QUERY_TYPE); mRawSql = builder.getRawSql(); mSelectionArgs = builder.getSelectionArgs(); } public RawQueryModel(final JsonWrapper wrapper) { super(wrapper, QUERY_TYPE); mRawSql = wrapper.getString(FIELD_RAW_SQL); mSelectionArgs = wrapper.getStringArray(FIELD_SELECTION_ARGS); } @Override protected Cursor executeQueryInternal(final SQLiteDatabase db) { return db.rawQuery(mRawSql, mSelectionArgs); } public String getRawSql() { return mRawSql; } public String[] getSelectionArgs() { return mSelectionArgs; } @Override public String toJson() throws JSONException { final JSONObject payload = new JSONObject(); addCommonFields(payload);
// Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/QueryModelInfo.java // public interface QueryModelInfo { // /** // * Gets the user specified comment of this Model // * // * @return the comment // */ // String getModelComment(); // // /** // * Gets the user specified tag of this Model // * // * @return the tag // */ // String getModelTag(); // // /** // * Gets the user specified version of this Model // * The default value is 0 // * // * @return the version of this model // */ // int getModelVersion(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querybuilders/interfaces/SqlRawQueryBuilder.java // public interface SqlRawQueryBuilder { // // EasyQueryModel build(); // // String getRawSql(); // // String[] getSelectionArgs(); // } // // Path: library/src/main/java/uk/co/alt236/easycursor/util/JsonPayloadHelper.java // public final class JsonPayloadHelper { // private static final String NULL = "null"; // // private JsonPayloadHelper() { // } // // public static void add(final JSONObject object, final String key, final Boolean value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Double value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Integer value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Long value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final Object value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String value) throws JSONException { // object.put(key, value); // } // // public static void add(final JSONObject object, final String key, final String[] value) throws JSONException { // final JSONArray arr = new JSONArray(); // // if (value != null && value.length > 0) { // for (final String str : value) { // arr.put(str); // } // } // // object.put(key, arr); // } // // // public static boolean getBoolean(final JSONObject object, final String key) { // return object.optBoolean(key, false); // } // // public static int getInt(final JSONObject object, final String key) { // return object.optInt(key, 0); // } // // public static String getString(final JSONObject object, final String key) { // final String res = object.optString(key, null); // if (key != null && key.equalsIgnoreCase(NULL)) { // return null; // } else { // return res; // } // } // // public static String[] getStringArray(final JSONObject payload, final String key) { // final JSONArray arr = payload.optJSONArray(key); // final String[] res; // // if (arr != null && arr.length() > 0) { // final int count = arr.length(); // res = new String[count]; // // for (int i = 0; i < count; i++) { // res[i] = arr.optString(i); // } // } else { // res = null; // } // // return res; // } // } // Path: library/src/main/java/uk/co/alt236/easycursor/sqlcursor/querymodels/RawQueryModel.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.QueryModelInfo; import uk.co.alt236.easycursor.sqlcursor.querybuilders.interfaces.SqlRawQueryBuilder; import uk.co.alt236.easycursor.util.JsonPayloadHelper; public RawQueryModel(final SqlRawQueryBuilder builder) { super(builder instanceof QueryModelInfo ? (QueryModelInfo) builder : null, QUERY_TYPE); mRawSql = builder.getRawSql(); mSelectionArgs = builder.getSelectionArgs(); } public RawQueryModel(final JsonWrapper wrapper) { super(wrapper, QUERY_TYPE); mRawSql = wrapper.getString(FIELD_RAW_SQL); mSelectionArgs = wrapper.getStringArray(FIELD_SELECTION_ARGS); } @Override protected Cursor executeQueryInternal(final SQLiteDatabase db) { return db.rawQuery(mRawSql, mSelectionArgs); } public String getRawSql() { return mRawSql; } public String[] getSelectionArgs() { return mSelectionArgs; } @Override public String toJson() throws JSONException { final JSONObject payload = new JSONObject(); addCommonFields(payload);
JsonPayloadHelper.add(payload, FIELD_RAW_SQL, getRawSql());
alt236/EasyCursor---Android
library/src/test/java/uk/co/alt236/easycursor/sqlcursor/factory/DatabaseHandler.java
// Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // }
import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; import uk.co.alt236.easycursor.objectcursor.factory.TestObject;
/* * *************************************************************************** * Copyright 2017 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.factory; public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = null; // IN-MEMORY // Contacts table name private static final String TABLE_DATA = "data"; // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_PH_NO = "phone_number";
// Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // } // Path: library/src/test/java/uk/co/alt236/easycursor/sqlcursor/factory/DatabaseHandler.java import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; import uk.co.alt236.easycursor.objectcursor.factory.TestObject; /* * *************************************************************************** * Copyright 2017 Alexandros Schillings * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 uk.co.alt236.easycursor.sqlcursor.factory; public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = null; // IN-MEMORY // Contacts table name private static final String TABLE_DATA = "data"; // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_PH_NO = "phone_number";
final List<TestObject> list = new ArrayList<>();
alt236/EasyCursor---Android
library/src/test/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverterTest.java
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // } // // Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // }
import junit.framework.TestCase; import java.nio.charset.Charset; import java.util.Arrays; import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import uk.co.alt236.easycursor.objectcursor.factory.TestObject;
assertEquals(expectedValue1, returnValue1); assertEquals(expectedValue2, returnValue2); } public void testShortByteArrayConversion() throws Exception { final short expectedValue1 = Short.MAX_VALUE; final short expectedValue2 = Short.MIN_VALUE; final byte[] byteArray1 = (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, expectedValue1); final byte[] byteArray2 = (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, expectedValue2); final short returnValue1 = (short) mObjectConverter.toType(ObjectType.SHORT, byteArray1); final short returnValue2 = (short) mObjectConverter.toType(ObjectType.SHORT, byteArray2); assertEquals(expectedValue1, returnValue1); assertEquals(expectedValue2, returnValue2); } public void testToBoolean() throws Exception { assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, true)); assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "true")); assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "TruE")); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, false)); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "false")); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "FalsE")); try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, 1)); fail("this should have blown");
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // } // // Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // } // Path: library/src/test/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverterTest.java import junit.framework.TestCase; import java.nio.charset.Charset; import java.util.Arrays; import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import uk.co.alt236.easycursor.objectcursor.factory.TestObject; assertEquals(expectedValue1, returnValue1); assertEquals(expectedValue2, returnValue2); } public void testShortByteArrayConversion() throws Exception { final short expectedValue1 = Short.MAX_VALUE; final short expectedValue2 = Short.MIN_VALUE; final byte[] byteArray1 = (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, expectedValue1); final byte[] byteArray2 = (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, expectedValue2); final short returnValue1 = (short) mObjectConverter.toType(ObjectType.SHORT, byteArray1); final short returnValue2 = (short) mObjectConverter.toType(ObjectType.SHORT, byteArray2); assertEquals(expectedValue1, returnValue1); assertEquals(expectedValue2, returnValue2); } public void testToBoolean() throws Exception { assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, true)); assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "true")); assertTrue((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "TruE")); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, false)); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "false")); assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "FalsE")); try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, 1)); fail("this should have blown");
} catch (final ConversionErrorException e) {
alt236/EasyCursor---Android
library/src/test/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverterTest.java
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // } // // Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // }
import junit.framework.TestCase; import java.nio.charset.Charset; import java.util.Arrays; import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import uk.co.alt236.easycursor.objectcursor.factory.TestObject;
assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "FalsE")); try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, 1)); fail("this should have blown"); } catch (final ConversionErrorException e) { // Expected } try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, null)); fail("this should have blown"); } catch (final ConversionErrorException e) { // Expected } } public void testToByteArray() throws Exception { assertNull(mObjectConverter.toType(ObjectType.BYTE_ARRAY, null)); final byte[] array = new byte[]{1, 2, 3, Byte.MAX_VALUE, Byte.MIN_VALUE}; assertTrue(Arrays.equals( array, (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, array))); assertTrue(Arrays.equals( new byte[]{116, 101, 115, 116}, (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, "test"))); try {
// Path: library/src/main/java/uk/co/alt236/easycursor/exceptions/ConversionErrorException.java // public class ConversionErrorException extends RuntimeException { // public ConversionErrorException(final String message) { // super(message); // } // // public ConversionErrorException(final Exception exception) { // super(exception); // } // } // // Path: library/src/test/java/uk/co/alt236/easycursor/objectcursor/factory/TestObject.java // public class TestObject { // private final String mString; // private final Boolean mBool; // private final byte[] mByte; // private final Double mDouble; // private final Float mFloat; // private final Integer mInt; // private final Long mLong; // private final Short mShort; // private final Object mNull = null; // // public TestObject(final long seed) { // final Random random = new Random(seed); // // mString = UUID.randomUUID().toString(); // mByte = mString.getBytes(); // mBool = random.nextBoolean(); // mLong = random.nextLong(); // mInt = random.nextInt(); // mDouble = random.nextDouble(); // mFloat = random.nextFloat(); // mShort = (short) random.nextInt(Short.MAX_VALUE + 1); // } // // public TestObject(final String mString, // final Boolean mBool, // final byte[] mByte, // final Double mDouble, // final Float mFloat, // final Integer mInt, // final Long mLong, // final Short mShort) { // // this.mString = mString; // this.mBool = mBool; // this.mByte = mByte; // this.mDouble = mDouble; // this.mFloat = mFloat; // this.mInt = mInt; // this.mLong = mLong; // this.mShort = mShort; // } // // public byte[] getByte() { // return mByte; // } // // public Double getDouble() { // return mDouble; // } // // public Float getFloat() { // return mFloat; // } // // public Integer getInt() { // return mInt; // } // // public Long getLong() { // return mLong; // } // // public Object getNull() { // return mNull; // } // // public Short getShort() { // return mShort; // } // // public String getString() { // return mString; // } // // public Boolean isBool() { // return mBool; // } // // public static class Builder { // private String mString; // private Boolean mBool; // private byte[] mByte; // private Double mDouble; // private Float mFloat; // private Integer mInt; // private Long mLong; // private Short mShort; // // public Builder() { // } // // public TestObject build() { // return new TestObject(mString, mBool, mByte, mDouble, mFloat, mInt, mLong, mShort); // } // // public Builder withBool(final Boolean mBool) { // this.mBool = mBool; // return this; // } // // public Builder withByte(final byte[] mByte) { // this.mByte = mByte; // return this; // } // // public Builder withDouble(final Double mDouble) { // this.mDouble = mDouble; // return this; // } // // public Builder withFloat(final Float mFloat) { // this.mFloat = mFloat; // return this; // } // // public Builder withInt(final Integer mInt) { // this.mInt = mInt; // return this; // } // // public Builder withLong(final Long mLong) { // this.mLong = mLong; // return this; // } // // public Builder withShort(final Short mShort) { // this.mShort = mShort; // return this; // } // // public Builder withString(final String mString) { // this.mString = mString; // return this; // } // } // } // Path: library/src/test/java/uk/co/alt236/easycursor/internal/conversion/ObjectConverterTest.java import junit.framework.TestCase; import java.nio.charset.Charset; import java.util.Arrays; import uk.co.alt236.easycursor.exceptions.ConversionErrorException; import uk.co.alt236.easycursor.objectcursor.factory.TestObject; assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, "FalsE")); try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, 1)); fail("this should have blown"); } catch (final ConversionErrorException e) { // Expected } try { assertFalse((boolean) mObjectConverter.toType(ObjectType.BOOLEAN, null)); fail("this should have blown"); } catch (final ConversionErrorException e) { // Expected } } public void testToByteArray() throws Exception { assertNull(mObjectConverter.toType(ObjectType.BYTE_ARRAY, null)); final byte[] array = new byte[]{1, 2, 3, Byte.MAX_VALUE, Byte.MIN_VALUE}; assertTrue(Arrays.equals( array, (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, array))); assertTrue(Arrays.equals( new byte[]{116, 101, 115, 116}, (byte[]) mObjectConverter.toType(ObjectType.BYTE_ARRAY, "test"))); try {
mObjectConverter.toType(ObjectType.BYTE_ARRAY, new TestObject(1));
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/ServletRequestBindingErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST;
package com.github.mkopylec.errorest.handling.errordata.http; public class ServletRequestBindingErrorDataProvider extends HttpClientErrorDataProvider<ServletRequestBindingException> { public ServletRequestBindingErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/ServletRequestBindingErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST; package com.github.mkopylec.errorest.handling.errordata.http; public class ServletRequestBindingErrorDataProvider extends HttpClientErrorDataProvider<ServletRequestBindingException> { public ServletRequestBindingErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(ServletRequestBindingException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/validation/MethodArgumentNotValidErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest;
package com.github.mkopylec.errorest.handling.errordata.validation; public class MethodArgumentNotValidErrorDataProvider extends BeanValidationErrorDataProvider<MethodArgumentNotValidException> { public MethodArgumentNotValidErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/validation/MethodArgumentNotValidErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; package com.github.mkopylec.errorest.handling.errordata.validation; public class MethodArgumentNotValidErrorDataProvider extends BeanValidationErrorDataProvider<MethodArgumentNotValidException> { public MethodArgumentNotValidErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(MethodArgumentNotValidException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MediaTypeNotSupportedErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.UNSUPPORTED_MEDIA_TYPE;
package com.github.mkopylec.errorest.handling.errordata.http; public class MediaTypeNotSupportedErrorDataProvider extends HttpClientErrorDataProvider<HttpMediaTypeNotSupportedException> { public MediaTypeNotSupportedErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MediaTypeNotSupportedErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.UNSUPPORTED_MEDIA_TYPE; package com.github.mkopylec.errorest.handling.errordata.http; public class MediaTypeNotSupportedErrorDataProvider extends HttpClientErrorDataProvider<HttpMediaTypeNotSupportedException> { public MediaTypeNotSupportedErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(HttpMediaTypeNotSupportedException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java
// Path: src/main/java/com/github/mkopylec/errorest/handling/utils/HttpUtils.java // public static String getHeadersAsText(HttpServletRequest request) { // Map<String, String> headers = new HashMap<>(); // Enumeration<String> names = request.getHeaderNames(); // while (names.hasMoreElements()) { // String name = names.nextElement(); // if (!name.equals(AUTHORIZATION)) { // headers.put(name, request.getHeader(name)); // } // } // return headers.toString(); // }
import org.springframework.core.Ordered; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.github.mkopylec.errorest.handling.utils.HttpUtils.getHeadersAsText;
package com.github.mkopylec.errorest.handling; public class RequestAttributeSettingFilter extends OncePerRequestFilter implements Ordered { public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { filterChain.doFilter(request, response); } catch (Throwable ex) {
// Path: src/main/java/com/github/mkopylec/errorest/handling/utils/HttpUtils.java // public static String getHeadersAsText(HttpServletRequest request) { // Map<String, String> headers = new HashMap<>(); // Enumeration<String> names = request.getHeaderNames(); // while (names.hasMoreElements()) { // String name = names.nextElement(); // if (!name.equals(AUTHORIZATION)) { // headers.put(name, request.getHeader(name)); // } // } // return headers.toString(); // } // Path: src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java import org.springframework.core.Ordered; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.github.mkopylec.errorest.handling.utils.HttpUtils.getHeadersAsText; package com.github.mkopylec.errorest.handling; public class RequestAttributeSettingFilter extends OncePerRequestFilter implements Ordered { public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { filterChain.doFilter(request, response); } catch (Throwable ex) {
request.setAttribute(REQUEST_HEADERS_ERROR_ATTRIBUTE, getHeadersAsText(request));
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/validation/BindExceptionErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest;
package com.github.mkopylec.errorest.handling.errordata.validation; /** * INFO: BindException will never be thrown when request body is annotated with @RequestBody. */ public class BindExceptionErrorDataProvider extends BeanValidationErrorDataProvider<BindException> { public BindExceptionErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/validation/BindExceptionErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; package com.github.mkopylec.errorest.handling.errordata.validation; /** * INFO: BindException will never be thrown when request body is annotated with @RequestBody. */ public class BindExceptionErrorDataProvider extends BeanValidationErrorDataProvider<BindException> { public BindExceptionErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(BindException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.client.HttpStatusCodeException; import java.io.IOException; import java.nio.charset.Charset; import static com.github.mkopylec.errorest.response.Errors.emptyErrors; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML;
package com.github.mkopylec.errorest.exceptions; public class ExternalHttpRequestException extends HttpStatusCodeException { private static final Logger log = getLogger(ExternalHttpRequestException.class); protected final HttpMethod method; protected final String url; protected final ObjectMapper jsonMapper; protected final XmlMapper xmlMapper;
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.client.HttpStatusCodeException; import java.io.IOException; import java.nio.charset.Charset; import static com.github.mkopylec.errorest.response.Errors.emptyErrors; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML; package com.github.mkopylec.errorest.exceptions; public class ExternalHttpRequestException extends HttpStatusCodeException { private static final Logger log = getLogger(ExternalHttpRequestException.class); protected final HttpMethod method; protected final String url; protected final ObjectMapper jsonMapper; protected final XmlMapper xmlMapper;
protected Errors errors;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.client.HttpStatusCodeException; import java.io.IOException; import java.nio.charset.Charset; import static com.github.mkopylec.errorest.response.Errors.emptyErrors; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML;
package com.github.mkopylec.errorest.exceptions; public class ExternalHttpRequestException extends HttpStatusCodeException { private static final Logger log = getLogger(ExternalHttpRequestException.class); protected final HttpMethod method; protected final String url; protected final ObjectMapper jsonMapper; protected final XmlMapper xmlMapper; protected Errors errors; public ExternalHttpRequestException(HttpMethod method, String url, HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset, ObjectMapper jsonMapper, XmlMapper xmlMapper) { super(statusCode, statusText, responseHeaders, responseBody, responseCharset); this.method = method; this.url = url; this.jsonMapper = jsonMapper; this.xmlMapper = xmlMapper; } public Errors getResponseBodyAsErrors() { if (errors != null) { return errors; } errors = parseResponseBody(); if (errors == null) {
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.client.HttpStatusCodeException; import java.io.IOException; import java.nio.charset.Charset; import static com.github.mkopylec.errorest.response.Errors.emptyErrors; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML; package com.github.mkopylec.errorest.exceptions; public class ExternalHttpRequestException extends HttpStatusCodeException { private static final Logger log = getLogger(ExternalHttpRequestException.class); protected final HttpMethod method; protected final String url; protected final ObjectMapper jsonMapper; protected final XmlMapper xmlMapper; protected Errors errors; public ExternalHttpRequestException(HttpMethod method, String url, HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset, ObjectMapper jsonMapper, XmlMapper xmlMapper) { super(statusCode, statusText, responseHeaders, responseBody, responseCharset); this.method = method; this.url = url; this.jsonMapper = jsonMapper; this.xmlMapper = xmlMapper; } public Errors getResponseBodyAsErrors() { if (errors != null) { return errors; } errors = parseResponseBody(); if (errors == null) {
return emptyErrors();
mkopylec/errorest-spring-boot-starter
src/test/java/com/github/mkopylec/errorest/application/SecurityConfiguration.java
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAccessDeniedHandler.java // public class ErrorestAccessDeniedHandler implements AccessDeniedHandler { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAccessDeniedHandler(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AccessDeniedException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAuthenticationEntryPoint.java // public class ErrorestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAuthenticationEntryPoint(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AuthenticationException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // }
import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAccessDeniedHandler; import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAuthenticationEntryPoint; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
package com.github.mkopylec.errorest.application; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAccessDeniedHandler.java // public class ErrorestAccessDeniedHandler implements AccessDeniedHandler { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAccessDeniedHandler(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AccessDeniedException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAuthenticationEntryPoint.java // public class ErrorestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAuthenticationEntryPoint(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AuthenticationException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // Path: src/test/java/com/github/mkopylec/errorest/application/SecurityConfiguration.java import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAccessDeniedHandler; import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAuthenticationEntryPoint; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; package com.github.mkopylec.errorest.application; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final ErrorestAuthenticationEntryPoint authenticationEntryPoint;
mkopylec/errorest-spring-boot-starter
src/test/java/com/github/mkopylec/errorest/application/SecurityConfiguration.java
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAccessDeniedHandler.java // public class ErrorestAccessDeniedHandler implements AccessDeniedHandler { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAccessDeniedHandler(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AccessDeniedException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAuthenticationEntryPoint.java // public class ErrorestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAuthenticationEntryPoint(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AuthenticationException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // }
import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAccessDeniedHandler; import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAuthenticationEntryPoint; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
package com.github.mkopylec.errorest.application; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final ErrorestAuthenticationEntryPoint authenticationEntryPoint;
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAccessDeniedHandler.java // public class ErrorestAccessDeniedHandler implements AccessDeniedHandler { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAccessDeniedHandler(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AccessDeniedException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorestAuthenticationEntryPoint.java // public class ErrorestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // protected final ErrorDataProviderContext providerContext; // protected final ErrorsFactory errorsFactory; // protected final ErrorsHttpResponseSetter responseBodySetter; // // public ErrorestAuthenticationEntryPoint(ErrorDataProviderContext providerContext, ErrorsFactory errorsFactory, ErrorsHttpResponseSetter responseBodySetter) { // this.providerContext = providerContext; // this.errorsFactory = errorsFactory; // this.responseBodySetter = responseBodySetter; // } // // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException { // ErrorData errorData = getErrorData(ex, request); // Errors errors = errorsFactory.logAndCreateErrors(errorData); // responseBodySetter.setErrorsResponse(errors, errorData.getResponseStatus(), request, response); // } // // @SuppressWarnings("unchecked") // protected ErrorData getErrorData(AuthenticationException ex, HttpServletRequest request) { // ErrorDataProvider provider = providerContext.getErrorDataProvider(ex); // return provider.getErrorData(ex, request); // } // } // Path: src/test/java/com/github/mkopylec/errorest/application/SecurityConfiguration.java import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAccessDeniedHandler; import com.github.mkopylec.errorest.handling.errordata.security.ErrorestAuthenticationEntryPoint; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; package com.github.mkopylec.errorest.application; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final ErrorestAuthenticationEntryPoint authenticationEntryPoint;
private final ErrorestAccessDeniedHandler accessDeniedHandler;
mkopylec/errorest-spring-boot-starter
src/test/java/com/github/mkopylec/errorest/application/Controller.java
// Path: src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java // public class ErrorestTemplate extends RestTemplate { // // protected ObjectMapper jsonMapper = json().build(); // protected XmlMapper xmlMapper = xml().build(); // // public ErrorestTemplate() { // super(); // } // // public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { // super(requestFactory); // } // // public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { // super(messageConverters); // } // // public void setJsonMapper(ObjectMapper jsonMapper) { // this.jsonMapper = jsonMapper; // } // // public void setXmlMapper(XmlMapper xmlMapper) { // this.xmlMapper = xmlMapper; // } // // @Override // protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { // try { // return super.doExecute(url, method, requestCallback, responseExtractor); // } catch (HttpStatusCodeException ex) { // throw createExternalHttpRequestException(method, url, ex); // } // } // // protected ExternalHttpRequestException createExternalHttpRequestException(HttpMethod method, URI url, HttpStatusCodeException ex) { // return new ExternalHttpRequestException(method, url.toString(), ex.getStatusCode(), ex.getStatusText(), ex.getResponseHeaders(), ex.getResponseBodyAsByteArray(), getCharset(ex), jsonMapper, xmlMapper); // } // // protected Charset getCharset(HttpStatusCodeException ex) { // MediaType contentType = ex.getResponseHeaders().getContentType(); // return contentType != null ? contentType.getCharset() : null; // } // }
import com.github.mkopylec.errorest.client.ErrorestTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestOperations; import javax.validation.Valid; import java.util.Map; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
package com.github.mkopylec.errorest.application; @RestController @RequestMapping("/controller") public class Controller {
// Path: src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java // public class ErrorestTemplate extends RestTemplate { // // protected ObjectMapper jsonMapper = json().build(); // protected XmlMapper xmlMapper = xml().build(); // // public ErrorestTemplate() { // super(); // } // // public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { // super(requestFactory); // } // // public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { // super(messageConverters); // } // // public void setJsonMapper(ObjectMapper jsonMapper) { // this.jsonMapper = jsonMapper; // } // // public void setXmlMapper(XmlMapper xmlMapper) { // this.xmlMapper = xmlMapper; // } // // @Override // protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { // try { // return super.doExecute(url, method, requestCallback, responseExtractor); // } catch (HttpStatusCodeException ex) { // throw createExternalHttpRequestException(method, url, ex); // } // } // // protected ExternalHttpRequestException createExternalHttpRequestException(HttpMethod method, URI url, HttpStatusCodeException ex) { // return new ExternalHttpRequestException(method, url.toString(), ex.getStatusCode(), ex.getStatusText(), ex.getResponseHeaders(), ex.getResponseBodyAsByteArray(), getCharset(ex), jsonMapper, xmlMapper); // } // // protected Charset getCharset(HttpStatusCodeException ex) { // MediaType contentType = ex.getResponseHeaders().getContentType(); // return contentType != null ? contentType.getCharset() : null; // } // } // Path: src/test/java/com/github/mkopylec/errorest/application/Controller.java import com.github.mkopylec.errorest.client.ErrorestTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestOperations; import javax.validation.Valid; import java.util.Map; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE; package com.github.mkopylec.errorest.application; @RestController @RequestMapping("/controller") public class Controller {
private final RestOperations rest = new ErrorestTemplate();
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/NoHandlerFoundErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.NOT_FOUND;
package com.github.mkopylec.errorest.handling.errordata.http; public class NoHandlerFoundErrorDataProvider extends HttpClientErrorDataProvider<NoHandlerFoundException> { public NoHandlerFoundErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/NoHandlerFoundErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.NOT_FOUND; package com.github.mkopylec.errorest.handling.errordata.http; public class NoHandlerFoundErrorDataProvider extends HttpClientErrorDataProvider<NoHandlerFoundException> { public NoHandlerFoundErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(NoHandlerFoundException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorsHttpResponseSetter.java
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.APPLICATION_XML; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; import static org.springframework.http.MediaType.parseMediaType; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.xml;
package com.github.mkopylec.errorest.handling.errordata.security; public class ErrorsHttpResponseSetter { private static final Logger log = getLogger(ErrorsHttpResponseSetter.class); protected ObjectMapper jsonMapper = json().build(); protected XmlMapper xmlMapper = xml().build();
// Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java // @JacksonXmlRootElement(localName = "body") // public class Errors { // // public static final String EMPTY_ERRORS_ID = "N/A"; // // protected final String id; // @JacksonXmlProperty(localName = "error") // @JacksonXmlElementWrapper(localName = "errors") // protected final List<Error> errors; // // @JsonCreator // public Errors( // @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, // @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors // ) { // hasText(id, "Empty errors ID"); // this.id = id; // this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors); // } // // public String getId() { // return id; // } // // public List<Error> getErrors() { // return errors; // } // // public boolean hasErrors() { // return !errors.isEmpty(); // } // // public boolean containsErrorCode(String code) { // return errors.stream().anyMatch(error -> error.hasCode(code)); // } // // public boolean containsErrorDescriptions() { // return errors.stream().anyMatch(Error::hasDescription); // } // // public boolean containsErrorDescription(String description) { // return errors.stream().anyMatch(error -> error.hasDescription(description)); // } // // @JsonIgnore // public boolean isEmpty() { // return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); // } // // public void formatErrors(ResponseBodyFormat bodyFormat) { // errors.forEach(error -> error.format(bodyFormat)); // } // // public static Errors emptyErrors() { // return new Errors(EMPTY_ERRORS_ID, emptyList()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Errors rhs = (Errors) obj; // return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.errors, rhs.errors) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .append(errors) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/ErrorsHttpResponseSetter.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.response.Errors; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.slf4j.LoggerFactory.getLogger; import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.APPLICATION_XML; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; import static org.springframework.http.MediaType.parseMediaType; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.xml; package com.github.mkopylec.errorest.handling.errordata.security; public class ErrorsHttpResponseSetter { private static final Logger log = getLogger(ErrorsHttpResponseSetter.class); protected ObjectMapper jsonMapper = json().build(); protected XmlMapper xmlMapper = xml().build();
public void setErrorsResponse(Errors errors, HttpStatus responseHttpStatus, HttpServletRequest request, HttpServletResponse response) throws IOException {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // }
import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
package com.github.mkopylec.errorest.handling.errordata; public class ErrorData { public static final int ERRORS_ID_LENGTH = 10; protected final String id;
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; package com.github.mkopylec.errorest.handling.errordata; public class ErrorData { public static final int ERRORS_ID_LENGTH = 10; protected final String id;
protected final LoggingLevel loggingLevel;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // }
import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
package com.github.mkopylec.errorest.handling.errordata; public class ErrorData { public static final int ERRORS_ID_LENGTH = 10; protected final String id; protected final LoggingLevel loggingLevel; protected final String requestMethod; protected final String requestUri; protected final HttpStatus responseStatus;
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; package com.github.mkopylec.errorest.handling.errordata; public class ErrorData { public static final int ERRORS_ID_LENGTH = 10; protected final String id; protected final LoggingLevel loggingLevel; protected final String requestMethod; protected final String requestUri; protected final HttpStatus responseStatus;
protected final List<Error> errors;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // }
import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
return loggingLevel == level; } public String getRequestMethod() { return requestMethod; } public String getRequestUri() { return requestUri; } public HttpStatus getResponseStatus() { return responseStatus; } public List<Error> getErrors() { return errors; } public Throwable getThrowable() { return throwable; } public static final class ErrorDataBuilder { protected String id; protected LoggingLevel loggingLevel; protected String requestMethod; protected String requestUri; protected HttpStatus responseStatus;
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; return loggingLevel == level; } public String getRequestMethod() { return requestMethod; } public String getRequestUri() { return requestUri; } public HttpStatus getResponseStatus() { return responseStatus; } public List<Error> getErrors() { return errors; } public Throwable getThrowable() { return throwable; } public static final class ErrorDataBuilder { protected String id; protected LoggingLevel loggingLevel; protected String requestMethod; protected String requestUri; protected HttpStatus responseStatus;
protected List<Error> errors = new ErrorsLoggingList();
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MediaTypeNotAcceptableErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.NOT_ACCEPTABLE;
package com.github.mkopylec.errorest.handling.errordata.http; public class MediaTypeNotAcceptableErrorDataProvider extends HttpClientErrorDataProvider<HttpMediaTypeNotAcceptableException> { public MediaTypeNotAcceptableErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MediaTypeNotAcceptableErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.NOT_ACCEPTABLE; package com.github.mkopylec.errorest.handling.errordata.http; public class MediaTypeNotAcceptableErrorDataProvider extends HttpClientErrorDataProvider<HttpMediaTypeNotAcceptableException> { public MediaTypeNotAcceptableErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(HttpMediaTypeNotAcceptableException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java // public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers";
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static com.github.mkopylec.errorest.handling.RequestAttributeSettingFilter.REQUEST_HEADERS_ERROR_ATTRIBUTE; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.springframework.web.context.request.WebRequest.SCOPE_REQUEST;
package com.github.mkopylec.errorest.handling.errordata; public abstract class ErrorDataProvider<T extends Throwable> { public static final String REQUEST_URI_ERROR_ATTRIBUTE = "path"; public static final String NOT_AVAILABLE_DATA = "[N/A]";
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java // public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers"; // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static com.github.mkopylec.errorest.handling.RequestAttributeSettingFilter.REQUEST_HEADERS_ERROR_ATTRIBUTE; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.springframework.web.context.request.WebRequest.SCOPE_REQUEST; package com.github.mkopylec.errorest.handling.errordata; public abstract class ErrorDataProvider<T extends Throwable> { public static final String REQUEST_URI_ERROR_ATTRIBUTE = "path"; public static final String NOT_AVAILABLE_DATA = "[N/A]";
protected final ErrorestProperties errorestProperties;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java // public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers";
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static com.github.mkopylec.errorest.handling.RequestAttributeSettingFilter.REQUEST_HEADERS_ERROR_ATTRIBUTE; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.springframework.web.context.request.WebRequest.SCOPE_REQUEST;
package com.github.mkopylec.errorest.handling.errordata; public abstract class ErrorDataProvider<T extends Throwable> { public static final String REQUEST_URI_ERROR_ATTRIBUTE = "path"; public static final String NOT_AVAILABLE_DATA = "[N/A]"; protected final ErrorestProperties errorestProperties; protected ErrorDataProvider(ErrorestProperties errorestProperties) { this.errorestProperties = errorestProperties; } public abstract ErrorData getErrorData(T ex, HttpServletRequest request); public abstract ErrorData getErrorData(T ex, HttpServletRequest request, HttpStatus defaultResponseStatus, ErrorAttributes errorAttributes, WebRequest webRequest); protected String getRequestUri(ErrorAttributes errorAttributes, WebRequest webRequest) { return errorAttributes.getErrorAttributes(webRequest, false).getOrDefault(REQUEST_URI_ERROR_ATTRIBUTE, NOT_AVAILABLE_DATA).toString(); } protected String getRequestHeaders(WebRequest webRequest) {
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/RequestAttributeSettingFilter.java // public static final String REQUEST_HEADERS_ERROR_ATTRIBUTE = RequestAttributeSettingFilter.class.getName() + ".headers"; // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static com.github.mkopylec.errorest.handling.RequestAttributeSettingFilter.REQUEST_HEADERS_ERROR_ATTRIBUTE; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.springframework.web.context.request.WebRequest.SCOPE_REQUEST; package com.github.mkopylec.errorest.handling.errordata; public abstract class ErrorDataProvider<T extends Throwable> { public static final String REQUEST_URI_ERROR_ATTRIBUTE = "path"; public static final String NOT_AVAILABLE_DATA = "[N/A]"; protected final ErrorestProperties errorestProperties; protected ErrorDataProvider(ErrorestProperties errorestProperties) { this.errorestProperties = errorestProperties; } public abstract ErrorData getErrorData(T ex, HttpServletRequest request); public abstract ErrorData getErrorData(T ex, HttpServletRequest request, HttpStatus defaultResponseStatus, ErrorAttributes errorAttributes, WebRequest webRequest); protected String getRequestUri(ErrorAttributes errorAttributes, WebRequest webRequest) { return errorAttributes.getErrorAttributes(webRequest, false).getOrDefault(REQUEST_URI_ERROR_ATTRIBUTE, NOT_AVAILABLE_DATA).toString(); } protected String getRequestHeaders(WebRequest webRequest) {
return getAttribute(REQUEST_HEADERS_ERROR_ATTRIBUTE, webRequest);
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationExceptionConfiguration.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // }
import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List;
package com.github.mkopylec.errorest.exceptions; public class ApplicationExceptionConfiguration { protected List<Error> errors = new ErrorsLoggingList(); protected HttpStatus responseHttpStatus;
// Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationExceptionConfiguration.java import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; package com.github.mkopylec.errorest.exceptions; public class ApplicationExceptionConfiguration { protected List<Error> errors = new ErrorsLoggingList(); protected HttpStatus responseHttpStatus;
protected LoggingLevel loggingLevel;
mkopylec/errorest-spring-boot-starter
src/test/java/com/github/mkopylec/errorest/application/ServletFilter.java
// Path: src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java // public class ErrorestTemplate extends RestTemplate { // // protected ObjectMapper jsonMapper = json().build(); // protected XmlMapper xmlMapper = xml().build(); // // public ErrorestTemplate() { // super(); // } // // public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { // super(requestFactory); // } // // public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { // super(messageConverters); // } // // public void setJsonMapper(ObjectMapper jsonMapper) { // this.jsonMapper = jsonMapper; // } // // public void setXmlMapper(XmlMapper xmlMapper) { // this.xmlMapper = xmlMapper; // } // // @Override // protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { // try { // return super.doExecute(url, method, requestCallback, responseExtractor); // } catch (HttpStatusCodeException ex) { // throw createExternalHttpRequestException(method, url, ex); // } // } // // protected ExternalHttpRequestException createExternalHttpRequestException(HttpMethod method, URI url, HttpStatusCodeException ex) { // return new ExternalHttpRequestException(method, url.toString(), ex.getStatusCode(), ex.getStatusText(), ex.getResponseHeaders(), ex.getResponseBodyAsByteArray(), getCharset(ex), jsonMapper, xmlMapper); // } // // protected Charset getCharset(HttpStatusCodeException ex) { // MediaType contentType = ex.getResponseHeaders().getContentType(); // return contentType != null ? contentType.getCharset() : null; // } // }
import com.github.mkopylec.errorest.client.ErrorestTemplate; import org.springframework.core.annotation.Order; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.client.RestOperations; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.springframework.boot.autoconfigure.security.SecurityProperties.DEFAULT_FILTER_ORDER; import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML; import static org.springframework.http.MediaType.TEXT_HTML; import static org.springframework.http.MediaType.TEXT_PLAIN;
package com.github.mkopylec.errorest.application; @Component @Order(DEFAULT_FILTER_ORDER - 1) public class ServletFilter extends OncePerRequestFilter {
// Path: src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java // public class ErrorestTemplate extends RestTemplate { // // protected ObjectMapper jsonMapper = json().build(); // protected XmlMapper xmlMapper = xml().build(); // // public ErrorestTemplate() { // super(); // } // // public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { // super(requestFactory); // } // // public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { // super(messageConverters); // } // // public void setJsonMapper(ObjectMapper jsonMapper) { // this.jsonMapper = jsonMapper; // } // // public void setXmlMapper(XmlMapper xmlMapper) { // this.xmlMapper = xmlMapper; // } // // @Override // protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { // try { // return super.doExecute(url, method, requestCallback, responseExtractor); // } catch (HttpStatusCodeException ex) { // throw createExternalHttpRequestException(method, url, ex); // } // } // // protected ExternalHttpRequestException createExternalHttpRequestException(HttpMethod method, URI url, HttpStatusCodeException ex) { // return new ExternalHttpRequestException(method, url.toString(), ex.getStatusCode(), ex.getStatusText(), ex.getResponseHeaders(), ex.getResponseBodyAsByteArray(), getCharset(ex), jsonMapper, xmlMapper); // } // // protected Charset getCharset(HttpStatusCodeException ex) { // MediaType contentType = ex.getResponseHeaders().getContentType(); // return contentType != null ? contentType.getCharset() : null; // } // } // Path: src/test/java/com/github/mkopylec/errorest/application/ServletFilter.java import com.github.mkopylec.errorest.client.ErrorestTemplate; import org.springframework.core.annotation.Order; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.client.RestOperations; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.springframework.boot.autoconfigure.security.SecurityProperties.DEFAULT_FILTER_ORDER; import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_XML; import static org.springframework.http.MediaType.TEXT_HTML; import static org.springframework.http.MediaType.TEXT_PLAIN; package com.github.mkopylec.errorest.application; @Component @Order(DEFAULT_FILTER_ORDER - 1) public class ServletFilter extends OncePerRequestFilter {
private final RestOperations rest = new ErrorestTemplate();
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MessageNotReadableErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST;
package com.github.mkopylec.errorest.handling.errordata.http; public class MessageNotReadableErrorDataProvider extends HttpClientErrorDataProvider<HttpMessageNotReadableException> { public MessageNotReadableErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MessageNotReadableErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST; package com.github.mkopylec.errorest.handling.errordata.http; public class MessageNotReadableErrorDataProvider extends HttpClientErrorDataProvider<HttpMessageNotReadableException> { public MessageNotReadableErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(HttpMessageNotReadableException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // }
import com.github.mkopylec.errorest.logging.LoggingLevel; import org.springframework.boot.context.properties.ConfigurationProperties; import static com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat.FULL; import static com.github.mkopylec.errorest.logging.LoggingLevel.WARN;
package com.github.mkopylec.errorest.configuration; /** * ErroREST configuration properties. */ @ConfigurationProperties("errorest") public class ErrorestProperties { /** * HTTP response body format. */ private ResponseBodyFormat responseBodyFormat = FULL; /** * Properties responsible for handling validation errors. */ private BeanValidationError beanValidationError = new BeanValidationError(); /** * Properties responsible for handling 4xx HTTP errors. */ private HttpClientError httpClientError = new HttpClientError(); public ResponseBodyFormat getResponseBodyFormat() { return responseBodyFormat; } public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { this.responseBodyFormat = responseBodyFormat; } public BeanValidationError getBeanValidationError() { return beanValidationError; } public void setBeanValidationError(BeanValidationError beanValidationError) { this.beanValidationError = beanValidationError; } public HttpClientError getHttpClientError() { return httpClientError; } public void setHttpClientError(HttpClientError httpClientError) { this.httpClientError = httpClientError; } public enum ResponseBodyFormat { WITHOUT_DESCRIPTIONS, FULL } public static class BeanValidationError { /** * Validation errors logging level. */
// Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java import com.github.mkopylec.errorest.logging.LoggingLevel; import org.springframework.boot.context.properties.ConfigurationProperties; import static com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat.FULL; import static com.github.mkopylec.errorest.logging.LoggingLevel.WARN; package com.github.mkopylec.errorest.configuration; /** * ErroREST configuration properties. */ @ConfigurationProperties("errorest") public class ErrorestProperties { /** * HTTP response body format. */ private ResponseBodyFormat responseBodyFormat = FULL; /** * Properties responsible for handling validation errors. */ private BeanValidationError beanValidationError = new BeanValidationError(); /** * Properties responsible for handling 4xx HTTP errors. */ private HttpClientError httpClientError = new HttpClientError(); public ResponseBodyFormat getResponseBodyFormat() { return responseBodyFormat; } public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { this.responseBodyFormat = responseBodyFormat; } public BeanValidationError getBeanValidationError() { return beanValidationError; } public void setBeanValidationError(BeanValidationError beanValidationError) { this.beanValidationError = beanValidationError; } public HttpClientError getHttpClientError() { return httpClientError; } public void setHttpClientError(HttpClientError httpClientError) { this.httpClientError = httpClientError; } public enum ResponseBodyFormat { WITHOUT_DESCRIPTIONS, FULL } public static class BeanValidationError { /** * Validation errors logging level. */
private LoggingLevel loggingLevel = WARN;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/RequestMethodNotSupportedErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED;
package com.github.mkopylec.errorest.handling.errordata.http; public class RequestMethodNotSupportedErrorDataProvider extends HttpClientErrorDataProvider<HttpRequestMethodNotSupportedException> { public RequestMethodNotSupportedErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/RequestMethodNotSupportedErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.join; import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED; package com.github.mkopylec.errorest.handling.errordata.http; public class RequestMethodNotSupportedErrorDataProvider extends HttpClientErrorDataProvider<HttpRequestMethodNotSupportedException> { public RequestMethodNotSupportedErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(HttpRequestMethodNotSupportedException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MissingServletRequestPartErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.support.MissingServletRequestPartException; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST;
package com.github.mkopylec.errorest.handling.errordata.http; public class MissingServletRequestPartErrorDataProvider extends HttpClientErrorDataProvider<MissingServletRequestPartException> { public MissingServletRequestPartErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MissingServletRequestPartErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.support.MissingServletRequestPartException; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST; package com.github.mkopylec.errorest.handling.errordata.http; public class MissingServletRequestPartErrorDataProvider extends HttpClientErrorDataProvider<MissingServletRequestPartException> { public MissingServletRequestPartErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(MissingServletRequestPartException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/response/Errors.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.List; import static java.util.Collections.emptyList; import static org.springframework.util.Assert.hasText;
package com.github.mkopylec.errorest.response; @JacksonXmlRootElement(localName = "body") public class Errors { public static final String EMPTY_ERRORS_ID = "N/A"; protected final String id; @JacksonXmlProperty(localName = "error") @JacksonXmlElementWrapper(localName = "errors") protected final List<Error> errors; @JsonCreator public Errors( @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors ) { hasText(id, "Empty errors ID"); this.id = id;
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.List; import static java.util.Collections.emptyList; import static org.springframework.util.Assert.hasText; package com.github.mkopylec.errorest.response; @JacksonXmlRootElement(localName = "body") public class Errors { public static final String EMPTY_ERRORS_ID = "N/A"; protected final String id; @JacksonXmlProperty(localName = "error") @JacksonXmlElementWrapper(localName = "errors") protected final List<Error> errors; @JsonCreator public Errors( @JsonProperty("id") @JacksonXmlProperty(localName = "id") String id, @JsonProperty("errors") @JacksonXmlProperty(localName = "Jackson bug workaround") List<Error> errors ) { hasText(id, "Empty errors ID"); this.id = id;
this.errors = errors == null ? new ErrorsLoggingList() : new ErrorsLoggingList(errors);
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/response/Errors.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.List; import static java.util.Collections.emptyList; import static org.springframework.util.Assert.hasText;
public String getId() { return id; } public List<Error> getErrors() { return errors; } public boolean hasErrors() { return !errors.isEmpty(); } public boolean containsErrorCode(String code) { return errors.stream().anyMatch(error -> error.hasCode(code)); } public boolean containsErrorDescriptions() { return errors.stream().anyMatch(Error::hasDescription); } public boolean containsErrorDescription(String description) { return errors.stream().anyMatch(error -> error.hasDescription(description)); } @JsonIgnore public boolean isEmpty() { return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); }
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // Path: src/main/java/com/github/mkopylec/errorest/logging/ErrorsLoggingList.java // public class ErrorsLoggingList extends ArrayList<Error> { // // public ErrorsLoggingList() { // super(1); // } // // public ErrorsLoggingList(Collection<? extends Error> c) { // super(c); // } // // @Override // public String toString() { // return stream().map(Error::toString).collect(joining(" | ")); // } // } // Path: src/main/java/com/github/mkopylec/errorest/response/Errors.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import com.github.mkopylec.errorest.logging.ErrorsLoggingList; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.List; import static java.util.Collections.emptyList; import static org.springframework.util.Assert.hasText; public String getId() { return id; } public List<Error> getErrors() { return errors; } public boolean hasErrors() { return !errors.isEmpty(); } public boolean containsErrorCode(String code) { return errors.stream().anyMatch(error -> error.hasCode(code)); } public boolean containsErrorDescriptions() { return errors.stream().anyMatch(Error::hasDescription); } public boolean containsErrorDescription(String description) { return errors.stream().anyMatch(error -> error.hasDescription(description)); } @JsonIgnore public boolean isEmpty() { return EMPTY_ERRORS_ID.equals(id) && !hasErrors(); }
public void formatErrors(ResponseBodyFormat bodyFormat) {
mkopylec/errorest-spring-boot-starter
src/test/java/com/github/mkopylec/errorest/application/TestApplicationException.java
// Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationException.java // public abstract class ApplicationException extends RuntimeException { // // protected final List<Error> errors; // protected final HttpStatus responseHttpStatus; // protected final LoggingLevel loggingLevel; // // public ApplicationException(ApplicationExceptionConfiguration configuration) { // this(configuration.getErrors(), configuration.getResponseHttpStatus(), configuration.getLoggingLevel(), configuration.getCause()); // } // // private ApplicationException(List<Error> errors, HttpStatus responseHttpStatus, LoggingLevel loggingLevel, Throwable cause) { // super(cause); // notEmpty(errors, "Empty errors"); // errors.forEach(error -> { // notNull(error, "Empty error"); // hasText(error.getCode(), "Empty error code"); // hasText(error.getDescription(), "Empty error description"); // }); // notNull(responseHttpStatus, "Empty response HTTP status"); // notNull(loggingLevel, "Empty logging level"); // this.errors = errors; // this.responseHttpStatus = responseHttpStatus; // this.loggingLevel = loggingLevel; // } // // public List<Error> getErrors() { // return errors; // } // // public HttpStatus getResponseHttpStatus() { // return responseHttpStatus; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // @Override // public String getMessage() { // return "An application error has occurred. Status: " + responseHttpStatus + " | " + errors; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationExceptionConfiguration.java // public class ApplicationExceptionConfiguration { // // protected List<Error> errors = new ErrorsLoggingList(); // protected HttpStatus responseHttpStatus; // protected LoggingLevel loggingLevel; // protected Throwable cause; // // protected List<Error> getErrors() { // return errors; // } // // public ApplicationExceptionConfiguration addError(String code, String description) { // errors.add(new Error(code, description)); // return this; // } // // public ApplicationExceptionConfiguration withErrors(ErrorsLoggingList errors) { // this.errors = errors; // return this; // } // // protected HttpStatus getResponseHttpStatus() { // return responseHttpStatus; // } // // public ApplicationExceptionConfiguration withResponseHttpStatus(HttpStatus responseHttpStatus) { // this.responseHttpStatus = responseHttpStatus; // return this; // } // // protected LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public ApplicationExceptionConfiguration withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // protected Throwable getCause() { // return cause; // } // // public ApplicationExceptionConfiguration withCause(Throwable cause) { // this.cause = cause; // return this; // } // }
import com.github.mkopylec.errorest.exceptions.ApplicationException; import com.github.mkopylec.errorest.exceptions.ApplicationExceptionConfiguration; import static com.github.mkopylec.errorest.logging.LoggingLevel.INFO; import static org.springframework.http.HttpStatus.I_AM_A_TEAPOT;
package com.github.mkopylec.errorest.application; public class TestApplicationException extends ApplicationException { public TestApplicationException() {
// Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationException.java // public abstract class ApplicationException extends RuntimeException { // // protected final List<Error> errors; // protected final HttpStatus responseHttpStatus; // protected final LoggingLevel loggingLevel; // // public ApplicationException(ApplicationExceptionConfiguration configuration) { // this(configuration.getErrors(), configuration.getResponseHttpStatus(), configuration.getLoggingLevel(), configuration.getCause()); // } // // private ApplicationException(List<Error> errors, HttpStatus responseHttpStatus, LoggingLevel loggingLevel, Throwable cause) { // super(cause); // notEmpty(errors, "Empty errors"); // errors.forEach(error -> { // notNull(error, "Empty error"); // hasText(error.getCode(), "Empty error code"); // hasText(error.getDescription(), "Empty error description"); // }); // notNull(responseHttpStatus, "Empty response HTTP status"); // notNull(loggingLevel, "Empty logging level"); // this.errors = errors; // this.responseHttpStatus = responseHttpStatus; // this.loggingLevel = loggingLevel; // } // // public List<Error> getErrors() { // return errors; // } // // public HttpStatus getResponseHttpStatus() { // return responseHttpStatus; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // @Override // public String getMessage() { // return "An application error has occurred. Status: " + responseHttpStatus + " | " + errors; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationExceptionConfiguration.java // public class ApplicationExceptionConfiguration { // // protected List<Error> errors = new ErrorsLoggingList(); // protected HttpStatus responseHttpStatus; // protected LoggingLevel loggingLevel; // protected Throwable cause; // // protected List<Error> getErrors() { // return errors; // } // // public ApplicationExceptionConfiguration addError(String code, String description) { // errors.add(new Error(code, description)); // return this; // } // // public ApplicationExceptionConfiguration withErrors(ErrorsLoggingList errors) { // this.errors = errors; // return this; // } // // protected HttpStatus getResponseHttpStatus() { // return responseHttpStatus; // } // // public ApplicationExceptionConfiguration withResponseHttpStatus(HttpStatus responseHttpStatus) { // this.responseHttpStatus = responseHttpStatus; // return this; // } // // protected LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public ApplicationExceptionConfiguration withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // protected Throwable getCause() { // return cause; // } // // public ApplicationExceptionConfiguration withCause(Throwable cause) { // this.cause = cause; // return this; // } // } // Path: src/test/java/com/github/mkopylec/errorest/application/TestApplicationException.java import com.github.mkopylec.errorest.exceptions.ApplicationException; import com.github.mkopylec.errorest.exceptions.ApplicationExceptionConfiguration; import static com.github.mkopylec.errorest.logging.LoggingLevel.INFO; import static org.springframework.http.HttpStatus.I_AM_A_TEAPOT; package com.github.mkopylec.errorest.application; public class TestApplicationException extends ApplicationException { public TestApplicationException() {
super(new ApplicationExceptionConfiguration()
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MissingServletRequestParameterErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST;
package com.github.mkopylec.errorest.handling.errordata.http; public class MissingServletRequestParameterErrorDataProvider extends HttpClientErrorDataProvider<MissingServletRequestParameterException> { public MissingServletRequestParameterErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/MissingServletRequestParameterErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST; package com.github.mkopylec.errorest.handling.errordata.http; public class MissingServletRequestParameterErrorDataProvider extends HttpClientErrorDataProvider<MissingServletRequestParameterException> { public MissingServletRequestParameterErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(MissingServletRequestParameterException ex, HttpServletRequest request) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationException.java
// Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // }
import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.springframework.util.Assert.hasText; import static org.springframework.util.Assert.notEmpty; import static org.springframework.util.Assert.notNull;
package com.github.mkopylec.errorest.exceptions; public abstract class ApplicationException extends RuntimeException { protected final List<Error> errors; protected final HttpStatus responseHttpStatus;
// Path: src/main/java/com/github/mkopylec/errorest/logging/LoggingLevel.java // public enum LoggingLevel { // // TRACE, DEBUG, INFO, WARN, ERROR // } // // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java // public class Error { // // public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; // // protected final String code; // protected String description; // // @JsonCreator // public Error( // @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, // @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description // ) { // this.code = code; // this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; // } // // public String getCode() { // return code; // } // // public boolean hasCode(String code) { // return this.code.equals(code); // } // // public String getDescription() { // return description; // } // // public boolean hasDescription() { // return !description.equals(DESCRIPTION_NOT_AVAILABLE); // } // // public boolean hasDescription(String description) { // return this.description.equals(description); // } // // public void format(ResponseBodyFormat bodyFormat) { // switch (bodyFormat) { // case FULL: // return; // case WITHOUT_DESCRIPTIONS: // description = DESCRIPTION_NOT_AVAILABLE; // return; // default: // throw new IllegalArgumentException("Unsupported response body format: " + bodyFormat); // } // } // // @Override // public String toString() { // return code + ": " + description; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Error rhs = (Error) obj; // return new EqualsBuilder() // .append(this.code, rhs.code) // .append(this.description, rhs.description) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(code) // .append(description) // .toHashCode(); // } // } // Path: src/main/java/com/github/mkopylec/errorest/exceptions/ApplicationException.java import com.github.mkopylec.errorest.logging.LoggingLevel; import com.github.mkopylec.errorest.response.Error; import org.springframework.http.HttpStatus; import java.util.List; import static org.springframework.util.Assert.hasText; import static org.springframework.util.Assert.notEmpty; import static org.springframework.util.Assert.notNull; package com.github.mkopylec.errorest.exceptions; public abstract class ApplicationException extends RuntimeException { protected final List<Error> errors; protected final HttpStatus responseHttpStatus;
protected final LoggingLevel loggingLevel;
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/SecurityErrorDataProviderContext.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AccessDeniedErrorDataProvider.java // public class AccessDeniedErrorDataProvider extends SecurityErrorDataProvider<AccessDeniedException> { // // public AccessDeniedErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return FORBIDDEN; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Access denied for request with headers: " + requestHeaders; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AuthenticationErrorDataProvider.java // public class AuthenticationErrorDataProvider extends SecurityErrorDataProvider<AuthenticationException> { // // public AuthenticationErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return UNAUTHORIZED; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Authentication failed for request with headers: " + requestHeaders; // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.security.AccessDeniedErrorDataProvider; import com.github.mkopylec.errorest.handling.errordata.security.AuthenticationErrorDataProvider; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException;
package com.github.mkopylec.errorest.handling.errordata; public class SecurityErrorDataProviderContext extends ErrorDataProviderContext { public SecurityErrorDataProviderContext(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) { if (ex instanceof AccessDeniedException) {
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AccessDeniedErrorDataProvider.java // public class AccessDeniedErrorDataProvider extends SecurityErrorDataProvider<AccessDeniedException> { // // public AccessDeniedErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return FORBIDDEN; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Access denied for request with headers: " + requestHeaders; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AuthenticationErrorDataProvider.java // public class AuthenticationErrorDataProvider extends SecurityErrorDataProvider<AuthenticationException> { // // public AuthenticationErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return UNAUTHORIZED; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Authentication failed for request with headers: " + requestHeaders; // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/SecurityErrorDataProviderContext.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.security.AccessDeniedErrorDataProvider; import com.github.mkopylec.errorest.handling.errordata.security.AuthenticationErrorDataProvider; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; package com.github.mkopylec.errorest.handling.errordata; public class SecurityErrorDataProviderContext extends ErrorDataProviderContext { public SecurityErrorDataProviderContext(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) { if (ex instanceof AccessDeniedException) {
return new AccessDeniedErrorDataProvider(errorestProperties);
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/SecurityErrorDataProviderContext.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AccessDeniedErrorDataProvider.java // public class AccessDeniedErrorDataProvider extends SecurityErrorDataProvider<AccessDeniedException> { // // public AccessDeniedErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return FORBIDDEN; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Access denied for request with headers: " + requestHeaders; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AuthenticationErrorDataProvider.java // public class AuthenticationErrorDataProvider extends SecurityErrorDataProvider<AuthenticationException> { // // public AuthenticationErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return UNAUTHORIZED; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Authentication failed for request with headers: " + requestHeaders; // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.security.AccessDeniedErrorDataProvider; import com.github.mkopylec.errorest.handling.errordata.security.AuthenticationErrorDataProvider; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException;
package com.github.mkopylec.errorest.handling.errordata; public class SecurityErrorDataProviderContext extends ErrorDataProviderContext { public SecurityErrorDataProviderContext(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) { if (ex instanceof AccessDeniedException) { return new AccessDeniedErrorDataProvider(errorestProperties); } if (ex instanceof AuthenticationException) {
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AccessDeniedErrorDataProvider.java // public class AccessDeniedErrorDataProvider extends SecurityErrorDataProvider<AccessDeniedException> { // // public AccessDeniedErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return FORBIDDEN; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Access denied for request with headers: " + requestHeaders; // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/security/AuthenticationErrorDataProvider.java // public class AuthenticationErrorDataProvider extends SecurityErrorDataProvider<AuthenticationException> { // // public AuthenticationErrorDataProvider(ErrorestProperties errorestProperties) { // super(errorestProperties); // } // // @Override // protected HttpStatus getResponseHttpStatus() { // return UNAUTHORIZED; // } // // @Override // protected String getErrorDescription(String requestHeaders) { // return "Authentication failed for request with headers: " + requestHeaders; // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/SecurityErrorDataProviderContext.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.security.AccessDeniedErrorDataProvider; import com.github.mkopylec.errorest.handling.errordata.security.AuthenticationErrorDataProvider; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; package com.github.mkopylec.errorest.handling.errordata; public class SecurityErrorDataProviderContext extends ErrorDataProviderContext { public SecurityErrorDataProviderContext(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) { if (ex instanceof AccessDeniedException) { return new AccessDeniedErrorDataProvider(errorestProperties); } if (ex instanceof AuthenticationException) {
return new AuthenticationErrorDataProvider(errorestProperties);
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/response/Error.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import static org.apache.commons.lang3.StringUtils.isNotBlank;
package com.github.mkopylec.errorest.response; public class Error { public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; protected final String code; protected String description; @JsonCreator public Error( @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description ) { this.code = code; this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; } public String getCode() { return code; } public boolean hasCode(String code) { return this.code.equals(code); } public String getDescription() { return description; } public boolean hasDescription() { return !description.equals(DESCRIPTION_NOT_AVAILABLE); } public boolean hasDescription(String description) { return this.description.equals(description); }
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // Path: src/main/java/com/github/mkopylec/errorest/response/Error.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.github.mkopylec.errorest.configuration.ErrorestProperties.ResponseBodyFormat; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import static org.apache.commons.lang3.StringUtils.isNotBlank; package com.github.mkopylec.errorest.response; public class Error { public static final String DESCRIPTION_NOT_AVAILABLE = "N/A"; protected final String code; protected String description; @JsonCreator public Error( @JsonProperty("code") @JacksonXmlProperty(localName = "code") String code, @JsonProperty("description") @JacksonXmlProperty(localName = "description") String description ) { this.code = code; this.description = isNotBlank(description) ? description : DESCRIPTION_NOT_AVAILABLE; } public String getCode() { return code; } public boolean hasCode(String code) { return this.code.equals(code); } public String getDescription() { return description; } public boolean hasDescription() { return !description.equals(DESCRIPTION_NOT_AVAILABLE); } public boolean hasDescription(String description) { return this.description.equals(description); }
public void format(ResponseBodyFormat bodyFormat) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java
// Path: src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java // public class ExternalHttpRequestException extends HttpStatusCodeException { // // private static final Logger log = getLogger(ExternalHttpRequestException.class); // // protected final HttpMethod method; // protected final String url; // protected final ObjectMapper jsonMapper; // protected final XmlMapper xmlMapper; // protected Errors errors; // // public ExternalHttpRequestException(HttpMethod method, String url, HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset, ObjectMapper jsonMapper, XmlMapper xmlMapper) { // super(statusCode, statusText, responseHeaders, responseBody, responseCharset); // this.method = method; // this.url = url; // this.jsonMapper = jsonMapper; // this.xmlMapper = xmlMapper; // } // // public Errors getResponseBodyAsErrors() { // if (errors != null) { // return errors; // } // errors = parseResponseBody(); // if (errors == null) { // return emptyErrors(); // } // return errors; // } // // @Override // public String getMessage() { // return "An external HTTP request has failed: " + method + " " + url + " " + getStatusCode() + ". Response body: " + getResponseBodyAsString(); // } // // protected Errors parseResponseBody() { // try { // if (hasContentType(APPLICATION_JSON)) { // return jsonMapper.readValue(getResponseBodyAsString(), Errors.class); // } // if (hasContentType(APPLICATION_XML)) { // return xmlMapper.readValue(getResponseBodyAsString(), Errors.class); // } // throw new IOException("Incompatible HTTP response " + CONTENT_TYPE + " header: " + getResponseHeaders().getContentType()); // } catch (IOException e) { // log.warn("Cannot convert HTTP response body to {}: {}", Errors.class.getName(), e.getMessage()); // return null; // } // } // // protected boolean hasContentType(MediaType mediaType) { // MediaType contentType = getResponseHeaders().getContentType(); // return contentType != null && contentType.includes(mediaType); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.exceptions.ExternalHttpRequestException; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.nio.charset.Charset; import java.util.List; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.xml;
package com.github.mkopylec.errorest.client; public class ErrorestTemplate extends RestTemplate { protected ObjectMapper jsonMapper = json().build(); protected XmlMapper xmlMapper = xml().build(); public ErrorestTemplate() { super(); } public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { super(requestFactory); } public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { super(messageConverters); } public void setJsonMapper(ObjectMapper jsonMapper) { this.jsonMapper = jsonMapper; } public void setXmlMapper(XmlMapper xmlMapper) { this.xmlMapper = xmlMapper; } @Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (HttpStatusCodeException ex) { throw createExternalHttpRequestException(method, url, ex); } }
// Path: src/main/java/com/github/mkopylec/errorest/exceptions/ExternalHttpRequestException.java // public class ExternalHttpRequestException extends HttpStatusCodeException { // // private static final Logger log = getLogger(ExternalHttpRequestException.class); // // protected final HttpMethod method; // protected final String url; // protected final ObjectMapper jsonMapper; // protected final XmlMapper xmlMapper; // protected Errors errors; // // public ExternalHttpRequestException(HttpMethod method, String url, HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset, ObjectMapper jsonMapper, XmlMapper xmlMapper) { // super(statusCode, statusText, responseHeaders, responseBody, responseCharset); // this.method = method; // this.url = url; // this.jsonMapper = jsonMapper; // this.xmlMapper = xmlMapper; // } // // public Errors getResponseBodyAsErrors() { // if (errors != null) { // return errors; // } // errors = parseResponseBody(); // if (errors == null) { // return emptyErrors(); // } // return errors; // } // // @Override // public String getMessage() { // return "An external HTTP request has failed: " + method + " " + url + " " + getStatusCode() + ". Response body: " + getResponseBodyAsString(); // } // // protected Errors parseResponseBody() { // try { // if (hasContentType(APPLICATION_JSON)) { // return jsonMapper.readValue(getResponseBodyAsString(), Errors.class); // } // if (hasContentType(APPLICATION_XML)) { // return xmlMapper.readValue(getResponseBodyAsString(), Errors.class); // } // throw new IOException("Incompatible HTTP response " + CONTENT_TYPE + " header: " + getResponseHeaders().getContentType()); // } catch (IOException e) { // log.warn("Cannot convert HTTP response body to {}: {}", Errors.class.getName(), e.getMessage()); // return null; // } // } // // protected boolean hasContentType(MediaType mediaType) { // MediaType contentType = getResponseHeaders().getContentType(); // return contentType != null && contentType.includes(mediaType); // } // } // Path: src/main/java/com/github/mkopylec/errorest/client/ErrorestTemplate.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.github.mkopylec.errorest.exceptions.ExternalHttpRequestException; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.nio.charset.Charset; import java.util.List; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.xml; package com.github.mkopylec.errorest.client; public class ErrorestTemplate extends RestTemplate { protected ObjectMapper jsonMapper = json().build(); protected XmlMapper xmlMapper = xml().build(); public ErrorestTemplate() { super(); } public ErrorestTemplate(ClientHttpRequestFactory requestFactory) { super(requestFactory); } public ErrorestTemplate(List<HttpMessageConverter<?>> messageConverters) { super(messageConverters); } public void setJsonMapper(ObjectMapper jsonMapper) { this.jsonMapper = jsonMapper; } public void setXmlMapper(XmlMapper xmlMapper) { this.xmlMapper = xmlMapper; } @Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (HttpStatusCodeException ex) { throw createExternalHttpRequestException(method, url, ex); } }
protected ExternalHttpRequestException createExternalHttpRequestException(HttpMethod method, URI url, HttpStatusCodeException ex) {
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/http/TypeMismatchErrorDataProvider.java
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.beans.TypeMismatchException; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST;
package com.github.mkopylec.errorest.handling.errordata.http; public class TypeMismatchErrorDataProvider extends HttpClientErrorDataProvider<TypeMismatchException> { public TypeMismatchErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
// Path: src/main/java/com/github/mkopylec/errorest/configuration/ErrorestProperties.java // @ConfigurationProperties("errorest") // public class ErrorestProperties { // // /** // * HTTP response body format. // */ // private ResponseBodyFormat responseBodyFormat = FULL; // /** // * Properties responsible for handling validation errors. // */ // private BeanValidationError beanValidationError = new BeanValidationError(); // /** // * Properties responsible for handling 4xx HTTP errors. // */ // private HttpClientError httpClientError = new HttpClientError(); // // public ResponseBodyFormat getResponseBodyFormat() { // return responseBodyFormat; // } // // public void setResponseBodyFormat(ResponseBodyFormat responseBodyFormat) { // this.responseBodyFormat = responseBodyFormat; // } // // public BeanValidationError getBeanValidationError() { // return beanValidationError; // } // // public void setBeanValidationError(BeanValidationError beanValidationError) { // this.beanValidationError = beanValidationError; // } // // public HttpClientError getHttpClientError() { // return httpClientError; // } // // public void setHttpClientError(HttpClientError httpClientError) { // this.httpClientError = httpClientError; // } // // public enum ResponseBodyFormat { // WITHOUT_DESCRIPTIONS, FULL // } // // public static class BeanValidationError { // // /** // * Validation errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // // public static class HttpClientError { // // /** // * HTTP 4xx errors logging level. // */ // private LoggingLevel loggingLevel = WARN; // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public void setLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // } // } // } // // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/http/TypeMismatchErrorDataProvider.java import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.springframework.beans.TypeMismatchException; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.springframework.http.HttpStatus.BAD_REQUEST; package com.github.mkopylec.errorest.handling.errordata.http; public class TypeMismatchErrorDataProvider extends HttpClientErrorDataProvider<TypeMismatchException> { public TypeMismatchErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } @Override
public ErrorData getErrorData(TypeMismatchException ex, HttpServletRequest request) {