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
mulesoft/mule-cookbook
webservice/src/main/java/com/cookbook/tutorial/service/IMuleCookBookService.java
// Path: model/src/main/java/com/cookbook/tutorial/customization/Description.java // public class Description { // // /** // * // */ // private String name; // private int entityId; // private DataType dataType; // private boolean isQuerable; // private boolean isSortable; // private String innerType; // private List<Description> innerFields; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DataType getDataType() { // return dataType; // } // // public void setDataType(DataType dataType) { // this.dataType = dataType; // } // // public boolean isQuerable() { // return isQuerable; // } // // public void setQuerable(boolean isQuerable) { // this.isQuerable = isQuerable; // } // // public boolean isSortable() { // return isSortable; // } // // public void setSortable(boolean isSortable) { // this.isSortable = isSortable; // } // // public String getInnerType() { // return innerType; // } // // public void setInnerType(String innerType) { // this.innerType = innerType; // } // // public List<Description> getInnerFields() { // return innerFields; // } // // public void setInnerFields(List<Description> innerFields) { // this.innerFields = innerFields; // } // } // // Path: model/src/main/java/com/cookbook/tutorial/model/CookBookEntity.java // @XmlSeeAlso({ Ingredient.class, Recipe.class }) // public abstract class CookBookEntity { // // /** // * Unique identifier of an Entity // */ // private Integer id; // // /** // * Date when it was created in the system. // */ // private Date created; // // /** // * Date of the last time it was modified // */ // private Date lastModified; // // /** // * Descriptive name of the entity. // */ // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Date getLastModified() { // return lastModified; // } // // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // } // // Path: model/src/main/java/com/cookbook/tutorial/model/Recipe.java // public class Recipe extends CookBookEntity{ // // /** // * List of ingredients required to make this recipe. // */ // private List<Ingredient> ingredients; // // /** // * Estimated time required to prepare it. // */ // private Double prepTime; // // /** // * Estimated time required to cook it. // */ // private Double cookTime; // // /** // * List of steps that you need to follow in order to make this recipe. // */ // private List<String> directions; // // public List<Ingredient> getIngredients() { // return ingredients; // } // // public void setIngredients(List<Ingredient> ingredients) { // this.ingredients = ingredients; // } // // public Double getPrepTime() { // return prepTime; // } // // public void setPrepTime(Double prepTime) { // this.prepTime = prepTime; // } // // public Double getCookTime() { // return cookTime; // } // // public void setCookTime(Double cookTime) { // this.cookTime = cookTime; // } // // public List<String> getDirections() { // return directions; // } // // public void setDirections(List<String> directions) { // this.directions = directions; // } // }
import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import com.cookbook.tutorial.customization.Description; import org.apache.cxf.annotations.WSDLDocumentation; import com.cookbook.tutorial.model.CookBookEntity; import com.cookbook.tutorial.model.Recipe; import java.util.List;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cookbook.tutorial.service; /** * Created by Mulesoft. */ @WebService @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public interface IMuleCookBookService { @WSDLDocumentation("Create an ingredient or recipe.")
// Path: model/src/main/java/com/cookbook/tutorial/customization/Description.java // public class Description { // // /** // * // */ // private String name; // private int entityId; // private DataType dataType; // private boolean isQuerable; // private boolean isSortable; // private String innerType; // private List<Description> innerFields; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DataType getDataType() { // return dataType; // } // // public void setDataType(DataType dataType) { // this.dataType = dataType; // } // // public boolean isQuerable() { // return isQuerable; // } // // public void setQuerable(boolean isQuerable) { // this.isQuerable = isQuerable; // } // // public boolean isSortable() { // return isSortable; // } // // public void setSortable(boolean isSortable) { // this.isSortable = isSortable; // } // // public String getInnerType() { // return innerType; // } // // public void setInnerType(String innerType) { // this.innerType = innerType; // } // // public List<Description> getInnerFields() { // return innerFields; // } // // public void setInnerFields(List<Description> innerFields) { // this.innerFields = innerFields; // } // } // // Path: model/src/main/java/com/cookbook/tutorial/model/CookBookEntity.java // @XmlSeeAlso({ Ingredient.class, Recipe.class }) // public abstract class CookBookEntity { // // /** // * Unique identifier of an Entity // */ // private Integer id; // // /** // * Date when it was created in the system. // */ // private Date created; // // /** // * Date of the last time it was modified // */ // private Date lastModified; // // /** // * Descriptive name of the entity. // */ // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Date getLastModified() { // return lastModified; // } // // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // } // // Path: model/src/main/java/com/cookbook/tutorial/model/Recipe.java // public class Recipe extends CookBookEntity{ // // /** // * List of ingredients required to make this recipe. // */ // private List<Ingredient> ingredients; // // /** // * Estimated time required to prepare it. // */ // private Double prepTime; // // /** // * Estimated time required to cook it. // */ // private Double cookTime; // // /** // * List of steps that you need to follow in order to make this recipe. // */ // private List<String> directions; // // public List<Ingredient> getIngredients() { // return ingredients; // } // // public void setIngredients(List<Ingredient> ingredients) { // this.ingredients = ingredients; // } // // public Double getPrepTime() { // return prepTime; // } // // public void setPrepTime(Double prepTime) { // this.prepTime = prepTime; // } // // public Double getCookTime() { // return cookTime; // } // // public void setCookTime(Double cookTime) { // this.cookTime = cookTime; // } // // public List<String> getDirections() { // return directions; // } // // public void setDirections(List<String> directions) { // this.directions = directions; // } // } // Path: webservice/src/main/java/com/cookbook/tutorial/service/IMuleCookBookService.java import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import com.cookbook.tutorial.customization.Description; import org.apache.cxf.annotations.WSDLDocumentation; import com.cookbook.tutorial.model.CookBookEntity; import com.cookbook.tutorial.model.Recipe; import java.util.List; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cookbook.tutorial.service; /** * Created by Mulesoft. */ @WebService @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public interface IMuleCookBookService { @WSDLDocumentation("Create an ingredient or recipe.")
CookBookEntity create(@WebParam(name = "entity") CookBookEntity entity,
ProductLayer/ProductLayer-SDK-for-Android
ply-android-common/src/main/java/com/productlayer/android/common/adapter/BrandAdapter.java
// Path: ply-android-common/src/main/java/com/productlayer/android/common/model/SimpleBrand.java // public class SimpleBrand { // // public String brand; // public String brandOwner; // // public String brandLower; // public String brandAlphaNumeric; // // /** // * Creates a new SimpleBrand instance. // * // * @param brand // * the name of the brand // * @param brandOwner // * the name of the owner of the brand // */ // public SimpleBrand(String brand, String brandOwner) { // this.brand = brand; // this.brandOwner = brandOwner; // brandLower = brand.toLowerCase(); // brandAlphaNumeric = brandLower.replaceAll("[^A-Za-z0-9 ]", ""); // } // // @Override // public String toString() { // return brand; // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.productlayer.android.common.R; import com.productlayer.android.common.model.SimpleBrand; import com.productlayer.core.beans.Brand; import com.productlayer.core.beans.BrandOwner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet;
/* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.adapter; /** * A filterable adapter of likely brands and their owners (returned first) as well as of all available brands * (returned last). The latter are shown only at a minimum input of one character. */ public class BrandAdapter extends BaseAdapter implements Filterable { private final LayoutInflater layoutInflater;
// Path: ply-android-common/src/main/java/com/productlayer/android/common/model/SimpleBrand.java // public class SimpleBrand { // // public String brand; // public String brandOwner; // // public String brandLower; // public String brandAlphaNumeric; // // /** // * Creates a new SimpleBrand instance. // * // * @param brand // * the name of the brand // * @param brandOwner // * the name of the owner of the brand // */ // public SimpleBrand(String brand, String brandOwner) { // this.brand = brand; // this.brandOwner = brandOwner; // brandLower = brand.toLowerCase(); // brandAlphaNumeric = brandLower.replaceAll("[^A-Za-z0-9 ]", ""); // } // // @Override // public String toString() { // return brand; // } // } // Path: ply-android-common/src/main/java/com/productlayer/android/common/adapter/BrandAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.productlayer.android.common.R; import com.productlayer.android.common.model.SimpleBrand; import com.productlayer.core.beans.Brand; import com.productlayer.core.beans.BrandOwner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; /* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.adapter; /** * A filterable adapter of likely brands and their owners (returned first) as well as of all available brands * (returned last). The latter are shown only at a minimum input of one character. */ public class BrandAdapter extends BaseAdapter implements Filterable { private final LayoutInflater layoutInflater;
private final Set<SimpleBrand> likelyBrands;
ProductLayer/ProductLayer-SDK-for-Android
ply-android-common/src/main/java/com/productlayer/android/common/model/Level.java
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/MathUtil.java // public class MathUtil { // // /** // * Returns the logarithm of a custom base for a given number. // * // * @param base // * the log base // * @param num // * the number // * @return the logarithm of a custom base for the given number // */ // public static double logOfBase(double base, double num) { // return Math.log(num) / Math.log(base); // } // // }
import com.productlayer.android.common.util.MathUtil;
/* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.model; /** * Encapsulates the level and advancement progress as parsed from the points of a user. */ public class Level { private long points; private double exactLevel; /** * Creates a new Level corresponding to the provided points value. * * @param points * the overall points earned to calculate the level from */ public Level(long points) { this.points = points;
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/MathUtil.java // public class MathUtil { // // /** // * Returns the logarithm of a custom base for a given number. // * // * @param base // * the log base // * @param num // * the number // * @return the logarithm of a custom base for the given number // */ // public static double logOfBase(double base, double num) { // return Math.log(num) / Math.log(base); // } // // } // Path: ply-android-common/src/main/java/com/productlayer/android/common/model/Level.java import com.productlayer.android.common.util.MathUtil; /* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.model; /** * Encapsulates the level and advancement progress as parsed from the points of a user. */ public class Level { private long points; private double exactLevel; /** * Creates a new Level corresponding to the provided points value. * * @param points * the overall points earned to calculate the level from */ public Level(long points) { this.points = points;
exactLevel = 1 + MathUtil.logOfBase(1.05, points + 6600) - MathUtil.logOfBase(1.05, 6600);
ProductLayer/ProductLayer-SDK-for-Android
ply-android-common/src/main/java/com/productlayer/android/common/activity/ScannerActivity.java
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/GTINUtil.java // public class GTINUtil { // // /** // * Extracts a GTIN from a GS1-128 (Code 128) formatted bar code. // * // * @param code // * the raw bar code value // * @return the extracted GTIN or null if none found // */ // public static String extractFromCode128(String code) { // if (code.length() < 16) { // return null; // } // if (code.startsWith("01") || code.startsWith("02")) { // return code.substring(2, 16); // } // return null; // } // // /** // * Extracts a GTIN from a GS1 DataMatrix formatted bar code. // * // * @param code // * the raw bar code value // * @return the extracted GTIN or null if none found // */ // public static String extractFromDataMatrix(String code) { // if (code.length() < 16) { // return null; // } // if (code.startsWith("01")) { // return code.substring(2, 16); // } // return null; // } // // /** // * Converts a UPC-E code to UPC-A. // * // * @param code // * the raw bar code value // * @return the extracted UPC-A code or null on any error // */ // public static String extractFromUPCE(String code) { // int len = code.length(); // String trimmed; // if (len == 6) { // trimmed = code; // } else if (len == 7) { // trimmed = code.substring(0, len - 1); // } else if (len == 8) { // trimmed = code.substring(1, len - 1); // } else { // return null; // } // char c1 = trimmed.charAt(0); // char c2 = trimmed.charAt(1); // char c3 = trimmed.charAt(2); // char c4 = trimmed.charAt(3); // char c5 = trimmed.charAt(4); // char c6 = trimmed.charAt(5); // String manufacturer; // String item; // switch (c6) { // case '0': // case '1': // case '2': // manufacturer = c1 + c2 + c6 + "00"; // item = "00" + c3 + c4 + c5; // break; // case '3': // manufacturer = c1 + c2 + c3 + "00"; // item = "000" + c4 + c5; // break; // case '4': // manufacturer = c1 + c2 + c3 + c4 + "0"; // item = "0000" + c5; // break; // default: // manufacturer = c1 + c2 + c3 + c4 + c5 + ""; // item = "0000" + c6; // } // String newCode = "0" + manufacturer + item; // return newCode + GTINValidator.calcChecksum(newCode.toCharArray(), newCode.length()); // } // // }
import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import com.productlayer.android.common.R; import com.productlayer.android.common.util.GTINUtil; import com.productlayer.core.error.PLYHttpException; import com.productlayer.core.logic.ProductLogic; import com.productlayer.core.utils.GTINValidator; import java.util.Arrays; import java.util.List; import me.dm7.barcodescanner.zxing.ZXingScannerView; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log;
super.onCreate(state); scannerView = new ZXingScannerView(this); scannerView.setFormats(supportedFormats); scannerView.setAutoFocus(true); setContentView(scannerView); } @Override protected void onResume() { super.onResume(); scannerView.setResultHandler(this); scannerView.startCamera(); //scannerView.setFlash(true); } @Override protected void onPause() { super.onPause(); scannerView.stopCamera(); } // ACTIVITY LIFECYCLE - END // @Override public void handleResult(Result result) { BarcodeFormat format = result.getBarcodeFormat(); String barcode = result.getText(); Log.i(getClass().getSimpleName(), "Scanned barcode from " + format + " with raw value " + barcode); String gtin; if (format == BarcodeFormat.CODE_128) {
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/GTINUtil.java // public class GTINUtil { // // /** // * Extracts a GTIN from a GS1-128 (Code 128) formatted bar code. // * // * @param code // * the raw bar code value // * @return the extracted GTIN or null if none found // */ // public static String extractFromCode128(String code) { // if (code.length() < 16) { // return null; // } // if (code.startsWith("01") || code.startsWith("02")) { // return code.substring(2, 16); // } // return null; // } // // /** // * Extracts a GTIN from a GS1 DataMatrix formatted bar code. // * // * @param code // * the raw bar code value // * @return the extracted GTIN or null if none found // */ // public static String extractFromDataMatrix(String code) { // if (code.length() < 16) { // return null; // } // if (code.startsWith("01")) { // return code.substring(2, 16); // } // return null; // } // // /** // * Converts a UPC-E code to UPC-A. // * // * @param code // * the raw bar code value // * @return the extracted UPC-A code or null on any error // */ // public static String extractFromUPCE(String code) { // int len = code.length(); // String trimmed; // if (len == 6) { // trimmed = code; // } else if (len == 7) { // trimmed = code.substring(0, len - 1); // } else if (len == 8) { // trimmed = code.substring(1, len - 1); // } else { // return null; // } // char c1 = trimmed.charAt(0); // char c2 = trimmed.charAt(1); // char c3 = trimmed.charAt(2); // char c4 = trimmed.charAt(3); // char c5 = trimmed.charAt(4); // char c6 = trimmed.charAt(5); // String manufacturer; // String item; // switch (c6) { // case '0': // case '1': // case '2': // manufacturer = c1 + c2 + c6 + "00"; // item = "00" + c3 + c4 + c5; // break; // case '3': // manufacturer = c1 + c2 + c3 + "00"; // item = "000" + c4 + c5; // break; // case '4': // manufacturer = c1 + c2 + c3 + c4 + "0"; // item = "0000" + c5; // break; // default: // manufacturer = c1 + c2 + c3 + c4 + c5 + ""; // item = "0000" + c6; // } // String newCode = "0" + manufacturer + item; // return newCode + GTINValidator.calcChecksum(newCode.toCharArray(), newCode.length()); // } // // } // Path: ply-android-common/src/main/java/com/productlayer/android/common/activity/ScannerActivity.java import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import com.productlayer.android.common.R; import com.productlayer.android.common.util.GTINUtil; import com.productlayer.core.error.PLYHttpException; import com.productlayer.core.logic.ProductLogic; import com.productlayer.core.utils.GTINValidator; import java.util.Arrays; import java.util.List; import me.dm7.barcodescanner.zxing.ZXingScannerView; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; super.onCreate(state); scannerView = new ZXingScannerView(this); scannerView.setFormats(supportedFormats); scannerView.setAutoFocus(true); setContentView(scannerView); } @Override protected void onResume() { super.onResume(); scannerView.setResultHandler(this); scannerView.startCamera(); //scannerView.setFlash(true); } @Override protected void onPause() { super.onPause(); scannerView.stopCamera(); } // ACTIVITY LIFECYCLE - END // @Override public void handleResult(Result result) { BarcodeFormat format = result.getBarcodeFormat(); String barcode = result.getText(); Log.i(getClass().getSimpleName(), "Scanned barcode from " + format + " with raw value " + barcode); String gtin; if (format == BarcodeFormat.CODE_128) {
gtin = GTINUtil.extractFromCode128(barcode);
ProductLayer/ProductLayer-SDK-for-Android
ply-android-common/src/main/java/com/productlayer/android/common/global/LoadingIndicator.java
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/ThreadUtil.java // public class ThreadUtil { // // /** // * @return whether the calling thread of this method equals the main (UI) thread // */ // public static boolean isMainThread() { // return Looper.myLooper() == Looper.getMainLooper(); // } // }
import java.lang.ref.WeakReference; import android.os.Handler; import android.view.View; import com.productlayer.android.common.util.ThreadUtil;
/* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.global; /** * Holds a weak reference to a widget to serve as the central loading indicator for components of the Common * module. */ public class LoadingIndicator { private static WeakReference<View> loadingIndicatorRef; private static Handler mainHandler; /** * Sets the loading indicator view to show and hide on command. This widget must be attached to the * activity's layout and must be at least on the same hierarchy level as overlapping views (it may be * hidden under sibling views). * * @param loadingIndicator * the view to show and hide on command * @param mainHandler * a handler associated with the main thread */ public static void set(View loadingIndicator, Handler mainHandler) { loadingIndicatorRef = new WeakReference<View>(loadingIndicator); LoadingIndicator.mainHandler = mainHandler; } /** * Brings the loading indicator to the front and makes it {@link View#VISIBLE}. */ public static void show() { final View loadingIndicator = getLoadingIndicator(); if (loadingIndicator == null) { return; }
// Path: ply-android-common/src/main/java/com/productlayer/android/common/util/ThreadUtil.java // public class ThreadUtil { // // /** // * @return whether the calling thread of this method equals the main (UI) thread // */ // public static boolean isMainThread() { // return Looper.myLooper() == Looper.getMainLooper(); // } // } // Path: ply-android-common/src/main/java/com/productlayer/android/common/global/LoadingIndicator.java import java.lang.ref.WeakReference; import android.os.Handler; import android.view.View; import com.productlayer.android.common.util.ThreadUtil; /* * Copyright (c) 2015, ProductLayer GmbH All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.productlayer.android.common.global; /** * Holds a weak reference to a widget to serve as the central loading indicator for components of the Common * module. */ public class LoadingIndicator { private static WeakReference<View> loadingIndicatorRef; private static Handler mainHandler; /** * Sets the loading indicator view to show and hide on command. This widget must be attached to the * activity's layout and must be at least on the same hierarchy level as overlapping views (it may be * hidden under sibling views). * * @param loadingIndicator * the view to show and hide on command * @param mainHandler * a handler associated with the main thread */ public static void set(View loadingIndicator, Handler mainHandler) { loadingIndicatorRef = new WeakReference<View>(loadingIndicator); LoadingIndicator.mainHandler = mainHandler; } /** * Brings the loading indicator to the front and makes it {@link View#VISIBLE}. */ public static void show() { final View loadingIndicator = getLoadingIndicator(); if (loadingIndicator == null) { return; }
if (ThreadUtil.isMainThread()) {
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/util/RequireUtilsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import org.junit.Test;
/* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class RequireUtilsTest { @Test(expected = IllegalArgumentException.class) public void nullArg() {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // Path: src/test/java/org/pdfsam/eventstudio/util/RequireUtilsTest.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import org.junit.Test; /* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class RequireUtilsTest { @Test(expected = IllegalArgumentException.class) public void nullArg() {
requireNotNull(null);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/util/RequireUtilsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import org.junit.Test;
/* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class RequireUtilsTest { @Test(expected = IllegalArgumentException.class) public void nullArg() { requireNotNull(null); } @Test(expected = IllegalArgumentException.class) public void blankArg() {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // Path: src/test/java/org/pdfsam/eventstudio/util/RequireUtilsTest.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import org.junit.Test; /* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class RequireUtilsTest { @Test(expected = IllegalArgumentException.class) public void nullArg() { requireNotNull(null); } @Test(expected = IllegalArgumentException.class) public void blankArg() {
requireNotBlank(" ");
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Envelope.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull;
/* * This file is part of the EventStudio source code * Created on 12/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Hold an event and the state of its notification * * @author Andrea Vacondio * */ class Envelope { private boolean notified = false; private final Object event; Envelope(Object event) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // Path: src/main/java/org/pdfsam/eventstudio/Envelope.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; /* * This file is part of the EventStudio source code * Created on 12/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Hold an event and the state of its notification * * @author Andrea Vacondio * */ class Envelope { private boolean notified = false; private final Object event; Envelope(Object event) {
requireNotNull(event);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java
// Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // }
import static org.pdfsam.eventstudio.util.StringUtils.isBlank;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * Utility class with some helper method to check validity of input arguments * * @author Andrea Vacondio * */ public final class RequireUtils { private RequireUtils() { // hide } /** * Requires that the input string is not blank * * @param victim the string to be tested * @throws IllegalArgumentException * if the input is blank */ public static void requireNotBlank(String victim) {
// Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java import static org.pdfsam.eventstudio.util.StringUtils.isBlank; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * Utility class with some helper method to check validity of input arguments * * @author Andrea Vacondio * */ public final class RequireUtils { private RequireUtils() { // hide } /** * Requires that the input string is not blank * * @param victim the string to be tested * @throws IllegalArgumentException * if the input is blank */ public static void requireNotBlank(String victim) {
if (isBlank(victim)) {
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/StationTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException;
} @Test(expected = IllegalArgumentException.class) public void nullAddAll() { victim.addAll(bean, null); } @Test public void supervisor() { Supervisor supervisor = mock(Supervisor.class); Object event = new Object(); victim.supervior(supervisor); victim.broadcast(event); verify(supervisor).inspect(event); } @Test public void addAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.add(Object.class, anotherMockListener, 0, ReferenceStrength.STRONG); victim.broadcast(event); verify(mockListener).onEvent(event); verify(anotherMockListener).onEvent(event); } @Test public void annotatedAddAndBroadcast() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestPrioritizedAnnotatedBean bean = new TestPrioritizedAnnotatedBean();
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/StationTest.java import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; } @Test(expected = IllegalArgumentException.class) public void nullAddAll() { victim.addAll(bean, null); } @Test public void supervisor() { Supervisor supervisor = mock(Supervisor.class); Object event = new Object(); victim.supervior(supervisor); victim.broadcast(event); verify(supervisor).inspect(event); } @Test public void addAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.add(Object.class, anotherMockListener, 0, ReferenceStrength.STRONG); victim.broadcast(event); verify(mockListener).onEvent(event); verify(anotherMockListener).onEvent(event); } @Test public void annotatedAddAndBroadcast() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestPrioritizedAnnotatedBean bean = new TestPrioritizedAnnotatedBean();
ReflectiveMetadata metadata = Annotations.process(bean);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/StationTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException;
verify(mockListener).onEvent(event); verify(anotherMockListener).onEvent(event); } @Test public void annotatedAddAndBroadcast() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestPrioritizedAnnotatedBean bean = new TestPrioritizedAnnotatedBean(); ReflectiveMetadata metadata = Annotations.process(bean); TestPrioritizedAnnotatedBean spy = spy(bean); victim.addAll(spy, metadata.getDescriptors().get("")); victim.broadcast(event); verify(spy).first(event); verify(spy).second(event); } @Test public void priority() { Object event = new Object(); InOrder inOrder = Mockito.inOrder(anotherMockListener, mockListener); victim.add(mockListener, 0, ReferenceStrength.STRONG); victim.add(anotherMockListener, -1, ReferenceStrength.STRONG); victim.broadcast(event); inOrder.verify(anotherMockListener).onEvent(event); inOrder.verify(mockListener).onEvent(event); } @Test public void broadcastInterrupted() { Object event = new Object();
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/StationTest.java import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; verify(mockListener).onEvent(event); verify(anotherMockListener).onEvent(event); } @Test public void annotatedAddAndBroadcast() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestPrioritizedAnnotatedBean bean = new TestPrioritizedAnnotatedBean(); ReflectiveMetadata metadata = Annotations.process(bean); TestPrioritizedAnnotatedBean spy = spy(bean); victim.addAll(spy, metadata.getDescriptors().get("")); victim.broadcast(event); verify(spy).first(event); verify(spy).second(event); } @Test public void priority() { Object event = new Object(); InOrder inOrder = Mockito.inOrder(anotherMockListener, mockListener); victim.add(mockListener, 0, ReferenceStrength.STRONG); victim.add(anotherMockListener, -1, ReferenceStrength.STRONG); victim.broadcast(event); inOrder.verify(anotherMockListener).onEvent(event); inOrder.verify(mockListener).onEvent(event); } @Test public void broadcastInterrupted() { Object event = new Object();
doThrow(BroadcastInterruptionException.class).when(anotherMockListener).onEvent(any());
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/StationTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException;
@Test public void broadcastInterruptedAnnotated() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestInterruptingPrioritizedAnnotatedBean bean = new TestInterruptingPrioritizedAnnotatedBean(); ReflectiveMetadata metadata = Annotations.process(bean); TestInterruptingPrioritizedAnnotatedBean spy = spy(bean); victim.addAll(spy, metadata.getDescriptors().get("")); victim.broadcast(event); verify(spy).first(event); verify(spy, never()).second(event); } @Test public void removeAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.remove(mockListener); victim.broadcast(event); verify(mockListener, never()).onEvent(event); } @Test public void removeExplicitAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.remove(Object.class, mockListener); victim.broadcast(event); verify(mockListener, never()).onEvent(event); }
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/StationTest.java import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.lang.reflect.InvocationTargetException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; @Test public void broadcastInterruptedAnnotated() throws IllegalAccessException, InvocationTargetException { Object event = new Object(); TestInterruptingPrioritizedAnnotatedBean bean = new TestInterruptingPrioritizedAnnotatedBean(); ReflectiveMetadata metadata = Annotations.process(bean); TestInterruptingPrioritizedAnnotatedBean spy = spy(bean); victim.addAll(spy, metadata.getDescriptors().get("")); victim.broadcast(event); verify(spy).first(event); verify(spy, never()).second(event); } @Test public void removeAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.remove(mockListener); victim.broadcast(event); verify(mockListener, never()).onEvent(event); } @Test public void removeExplicitAndBroadcast() { Object event = new Object(); victim.add(Object.class, mockListener, 0, ReferenceStrength.STRONG); victim.remove(Object.class, mockListener); victim.broadcast(event); verify(mockListener, never()).onEvent(event); }
@Test(expected = EventStudioException.class)
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Entity.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.ref.Reference;
/* * This file is part of the EventStudio source code * Created on 12/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Holder for an instance. * * @author Andrea Vacondio * @param <T> * the type of the referent */ interface Entity<T> { /** * @return the instance or null if nothing is available */ T get(); /** * Holds an entity referenced using the input {@link Reference} * * @author Andrea Vacondio * * @param <T> */ class ReferencedEntity<T> implements Entity<T> { private final Reference<T> reference; ReferencedEntity(Reference<T> reference) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // Path: src/main/java/org/pdfsam/eventstudio/Entity.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.ref.Reference; /* * This file is part of the EventStudio source code * Created on 12/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Holder for an instance. * * @author Andrea Vacondio * @param <T> * the type of the referent */ interface Entity<T> { /** * @return the instance or null if nothing is available */ T get(); /** * Holds an entity referenced using the input {@link Reference} * * @author Andrea Vacondio * * @param <T> */ class ReferencedEntity<T> implements Entity<T> { private final Reference<T> reference; ReferencedEntity(Reference<T> reference) {
requireNotNull(reference);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Annotations.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
/* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Utility methods processing beans to find annotated method or fields and register reflective listeners. * * @author Andrea Vacondio */ final class Annotations { private static final Logger LOG = LoggerFactory.getLogger(Annotations.class); private Annotations() { // utility } public static ReflectiveMetadata process(Object bean) throws IllegalAccessException, InvocationTargetException {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Utility methods processing beans to find annotated method or fields and register reflective listeners. * * @author Andrea Vacondio */ final class Annotations { private static final Logger LOG = LoggerFactory.getLogger(Annotations.class); private Annotations() { // utility } public static ReflectiveMetadata process(Object bean) throws IllegalAccessException, InvocationTargetException {
requireNotNull(bean);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Annotations.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
/* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Utility methods processing beans to find annotated method or fields and register reflective listeners. * * @author Andrea Vacondio */ final class Annotations { private static final Logger LOG = LoggerFactory.getLogger(Annotations.class); private Annotations() { // utility } public static ReflectiveMetadata process(Object bean) throws IllegalAccessException, InvocationTargetException { requireNotNull(bean); LOG.trace("Processing {} for annotated listeners", bean); // TODO process public and private String station = getStationNameFromFieldIfAny(bean); ReflectiveMetadata metadata = new ReflectiveMetadata(); for (Method method : getMethods(bean)) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Utility methods processing beans to find annotated method or fields and register reflective listeners. * * @author Andrea Vacondio */ final class Annotations { private static final Logger LOG = LoggerFactory.getLogger(Annotations.class); private Annotations() { // utility } public static ReflectiveMetadata process(Object bean) throws IllegalAccessException, InvocationTargetException { requireNotNull(bean); LOG.trace("Processing {} for annotated listeners", bean); // TODO process public and private String station = getStationNameFromFieldIfAny(bean); ReflectiveMetadata metadata = new ReflectiveMetadata(); for (Method method : getMethods(bean)) {
if (isBlank(station)) {
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Annotations.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
String station = getStationNameFromFieldIfAny(bean); ReflectiveMetadata metadata = new ReflectiveMetadata(); for (Method method : getMethods(bean)) { if (isBlank(station)) { station = getStationNameIfAnnotated(method, bean); } addIfAnnotated(metadata, method); } metadata.station = station; return metadata; } /** * @return a list containing all the public methods (inherited and not) and all the private, package and protected (not inherited) methods of the given bean */ private static List<Method> getMethods(Object bean) { List<Method> methods = new LinkedList<>(Arrays.asList(bean.getClass().getMethods())); for (Method method : bean.getClass().getDeclaredMethods()) { if (!Modifier.isPublic(method.getModifiers())) { methods.add(method); } } return methods; } private static void addIfAnnotated(ReflectiveMetadata metadata, Method method) { EventListener listenerAnnotation = method.getAnnotation(EventListener.class); if (listenerAnnotation != null) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static boolean isBlank(String input) { // return input == null || input.trim().length() <= 0; // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.isBlank; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; String station = getStationNameFromFieldIfAny(bean); ReflectiveMetadata metadata = new ReflectiveMetadata(); for (Method method : getMethods(bean)) { if (isBlank(station)) { station = getStationNameIfAnnotated(method, bean); } addIfAnnotated(metadata, method); } metadata.station = station; return metadata; } /** * @return a list containing all the public methods (inherited and not) and all the private, package and protected (not inherited) methods of the given bean */ private static List<Method> getMethods(Object bean) { List<Method> methods = new LinkedList<>(Arrays.asList(bean.getClass().getMethods())); for (Method method : bean.getClass().getDeclaredMethods()) { if (!Modifier.isPublic(method.getModifiers())) { methods.add(method); } } return methods; } private static void addIfAnnotated(ReflectiveMetadata metadata, Method method) { EventListener listenerAnnotation = method.getAnnotation(EventListener.class); if (listenerAnnotation != null) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1) {
throw new EventStudioException(
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/ListenersTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener;
public void remove() { TestListener listener = new TestListener(); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.remove(TestEvent.class, listener); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); } @Test public void removeMany() { TestListener listener = new TestListener(); SecondTestListener listener2 = new SecondTestListener(); AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, listener2, 0, ReferenceStrength.WEAK); victim.add(AnotherTestEvent.class, anotherListener, 0, ReferenceStrength.SOFT); assertFalse(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); assertFalse(victim.nullSafeGetListeners(AnotherTestEvent.class).isEmpty()); assertTrue(victim.remove(TestEvent.class, listener2)); assertTrue(victim.remove(AnotherTestEvent.class, anotherListener)); assertTrue(victim.nullSafeGetListeners(AnotherTestEvent.class).isEmpty()); assertEquals(1, victim.nullSafeGetListeners(TestEvent.class).size()); } @Test public void removeHolder() { TestListener listener = new TestListener(); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG);
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // } // Path: src/test/java/org/pdfsam/eventstudio/ListenersTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener; public void remove() { TestListener listener = new TestListener(); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.remove(TestEvent.class, listener); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); } @Test public void removeMany() { TestListener listener = new TestListener(); SecondTestListener listener2 = new SecondTestListener(); AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, listener2, 0, ReferenceStrength.WEAK); victim.add(AnotherTestEvent.class, anotherListener, 0, ReferenceStrength.SOFT); assertFalse(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); assertFalse(victim.nullSafeGetListeners(AnotherTestEvent.class).isEmpty()); assertTrue(victim.remove(TestEvent.class, listener2)); assertTrue(victim.remove(AnotherTestEvent.class, anotherListener)); assertTrue(victim.nullSafeGetListeners(AnotherTestEvent.class).isEmpty()); assertEquals(1, victim.nullSafeGetListeners(TestEvent.class).size()); } @Test public void removeHolder() { TestListener listener = new TestListener(); assertTrue(victim.nullSafeGetListeners(TestEvent.class).isEmpty()); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG);
for (ListenerReferenceHolder holder : victim.nullSafeGetListeners(TestEvent.class)) {
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/ListenersTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener;
TestListener listener = new TestListener(); AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.remove(AnotherTestEvent.class, anotherListener)); } @Test public void priorityOrder() throws IllegalAccessException, InvocationTargetException { TestListener prio0 = new TestListener(); TestListener prio1 = new TestListener(); TestListener prio2 = new TestListener(); TestListener prio3 = new TestListener(); TestListener prio4 = new TestListener(); TestListener prio5 = new TestListener(); TestListener prio6 = new TestListener(); TestListener prio7 = new TestListener(); TestListener prio8 = new TestListener(); TestListener prio9 = new TestListener(); victim.add(TestEvent.class, prio7, 7, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio9, 9, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio0, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio1, 1, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio2, 2, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio5, 5, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio6, 6, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio8, 8, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio3, 3, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio4, 4, ReferenceStrength.STRONG); ReflectiveTestListener bean = new ReflectiveTestListener();
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // } // Path: src/test/java/org/pdfsam/eventstudio/ListenersTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener; TestListener listener = new TestListener(); AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.remove(AnotherTestEvent.class, anotherListener)); } @Test public void priorityOrder() throws IllegalAccessException, InvocationTargetException { TestListener prio0 = new TestListener(); TestListener prio1 = new TestListener(); TestListener prio2 = new TestListener(); TestListener prio3 = new TestListener(); TestListener prio4 = new TestListener(); TestListener prio5 = new TestListener(); TestListener prio6 = new TestListener(); TestListener prio7 = new TestListener(); TestListener prio8 = new TestListener(); TestListener prio9 = new TestListener(); victim.add(TestEvent.class, prio7, 7, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio9, 9, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio0, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio1, 1, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio2, 2, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio5, 5, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio6, 6, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio8, 8, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio3, 3, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio4, 4, ReferenceStrength.STRONG); ReflectiveTestListener bean = new ReflectiveTestListener();
ReflectiveMetadata metadata = Annotations.process(bean);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/ListenersTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener;
AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.remove(AnotherTestEvent.class, anotherListener)); } @Test public void priorityOrder() throws IllegalAccessException, InvocationTargetException { TestListener prio0 = new TestListener(); TestListener prio1 = new TestListener(); TestListener prio2 = new TestListener(); TestListener prio3 = new TestListener(); TestListener prio4 = new TestListener(); TestListener prio5 = new TestListener(); TestListener prio6 = new TestListener(); TestListener prio7 = new TestListener(); TestListener prio8 = new TestListener(); TestListener prio9 = new TestListener(); victim.add(TestEvent.class, prio7, 7, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio9, 9, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio0, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio1, 1, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio2, 2, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio5, 5, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio6, 6, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio8, 8, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio3, 3, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio4, 4, ReferenceStrength.STRONG); ReflectiveTestListener bean = new ReflectiveTestListener(); ReflectiveMetadata metadata = Annotations.process(bean);
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java // static class ListenerReferenceHolder implements Comparable<ListenerReferenceHolder> { // int priority = 0; // private final Entity<? extends ListenerWrapper> reference; // // public ListenerReferenceHolder(int priority, Entity<? extends ListenerWrapper> reference) { // requireNotNull(reference); // this.priority = priority; // this.reference = reference; // } // // public int compareTo(ListenerReferenceHolder o) { // if (this.priority < o.priority) { // return -1; // } // if (this.priority > o.priority) { // return 1; // } // // same priority // int retVal = this.hashCode() - o.hashCode(); // // same hashcode but not equals. This shouldn't happen but according // // to hascode documentation is not required and since we don't want // // ListenerReferenceHolder to // // disappear from the TreeSet we return an arbitrary integer != from // // 0 // if (retVal == 0 && !this.equals(o)) { // retVal = -1; // } // return retVal; // } // // public ListenerWrapper getListenerWrapper() { // return reference.get(); // } // } // Path: src/test/java/org/pdfsam/eventstudio/ListenersTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Before; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.Listeners.ListenerReferenceHolder; import org.pdfsam.eventstudio.annotation.EventListener; AnotherTestListener anotherListener = new AnotherTestListener(); victim.add(TestEvent.class, listener, 0, ReferenceStrength.STRONG); assertFalse(victim.remove(AnotherTestEvent.class, anotherListener)); } @Test public void priorityOrder() throws IllegalAccessException, InvocationTargetException { TestListener prio0 = new TestListener(); TestListener prio1 = new TestListener(); TestListener prio2 = new TestListener(); TestListener prio3 = new TestListener(); TestListener prio4 = new TestListener(); TestListener prio5 = new TestListener(); TestListener prio6 = new TestListener(); TestListener prio7 = new TestListener(); TestListener prio8 = new TestListener(); TestListener prio9 = new TestListener(); victim.add(TestEvent.class, prio7, 7, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio9, 9, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio0, 0, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio1, 1, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio2, 2, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio5, 5, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio6, 6, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio8, 8, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio3, 3, ReferenceStrength.STRONG); victim.add(TestEvent.class, prio4, 4, ReferenceStrength.STRONG); ReflectiveTestListener bean = new ReflectiveTestListener(); ReflectiveMetadata metadata = Annotations.process(bean);
for (List<ReflectiveListenerDescriptor> descriptors : metadata.getDescriptors().values()) {
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Stations.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * A thread safe holder for {@link Station}. Provides methods to access to the {@link Station}s of the {@link EventStudio} creating a new one when requred. * * @author Andrea Vacondio * */ class Stations { private static final Logger LOG = LoggerFactory.getLogger(Stations.class); private final ConcurrentMap<String, Station> stations = new ConcurrentHashMap<>(); /** * @return the station with the given name. It safely creates a new {@link Station} if a station with the given name does not exist. * @throws IllegalArgumentException * if the station name is blank or null */ Station getStation(String stationName) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotBlank(String victim) { // if (isBlank(victim)) { // throw new IllegalArgumentException("The input string cannot be blank"); // } // } // Path: src/main/java/org/pdfsam/eventstudio/Stations.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotBlank; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * A thread safe holder for {@link Station}. Provides methods to access to the {@link Station}s of the {@link EventStudio} creating a new one when requred. * * @author Andrea Vacondio * */ class Stations { private static final Logger LOG = LoggerFactory.getLogger(Stations.class); private final ConcurrentMap<String, Station> stations = new ConcurrentHashMap<>(); /** * @return the station with the given name. It safely creates a new {@link Station} if a station with the given name does not exist. * @throws IllegalArgumentException * if the station name is blank or null */ Station getStation(String stationName) {
requireNotBlank(stationName);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/util/ReflectionUtilsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Listener.java // public interface Listener<T> { // // /** // * Notify the listener of the given event // */ // void onEvent(T event); // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import org.pdfsam.eventstudio.Listener;
/* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class ReflectionUtilsTest { @Test public void testInfer() { TestListener victim = new TestListener(); assertEquals(TestEvent.class, ReflectionUtils.inferParameterClass(victim.getClass(), "onEvent")); } @Test public void testFailingInfer() { SecondTestListener<TestEvent> victim = new SecondTestListener<>(); assertNull(ReflectionUtils.inferParameterClass(victim.getClass(), "onEvent")); }
// Path: src/main/java/org/pdfsam/eventstudio/Listener.java // public interface Listener<T> { // // /** // * Notify the listener of the given event // */ // void onEvent(T event); // } // Path: src/test/java/org/pdfsam/eventstudio/util/ReflectionUtilsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import org.pdfsam.eventstudio.Listener; /* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.util; /** * @author Andrea Vacondio * */ public class ReflectionUtilsTest { @Test public void testInfer() { TestListener victim = new TestListener(); assertEquals(TestEvent.class, ReflectionUtils.inferParameterClass(victim.getClass(), "onEvent")); } @Test public void testFailingInfer() { SecondTestListener<TestEvent> victim = new SecondTestListener<>(); assertNull(ReflectionUtils.inferParameterClass(victim.getClass(), "onEvent")); }
private class TestListener implements Listener<TestEvent> {
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try {
ReflectiveMetadata metadata = Annotations.process(bean);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean);
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean);
for (Entry<String, List<ReflectiveListenerDescriptor>> current : metadata.getDescriptors().entrySet()) {
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean); for (Entry<String, List<ReflectiveListenerDescriptor>> current : metadata.getDescriptors().entrySet()) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean); for (Entry<String, List<ReflectiveListenerDescriptor>> current : metadata.getDescriptors().entrySet()) {
String station = defaultString(metadata.getStation(), HIDDEN_STATION);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean); for (Entry<String, List<ReflectiveListenerDescriptor>> current : metadata.getDescriptors().entrySet()) { String station = defaultString(metadata.getStation(), HIDDEN_STATION); stations.getStation(defaultString(current.getKey(), station)).addAll(bean, current.getValue()); } } catch (IllegalAccessException | InvocationTargetException e) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 10/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * Default implementation of {@link EventStudio}. It doesn't enforce a Singleton pattern and it's up to the user to decide how to use it and how many EventStudio the application * needs. A singleton implementation with lazy initialization is provided with {@link org.pdfsam.eventstudio.StaticStudio} where the typical usage is: * * <pre> * {@code * import static org.eventstudio.StaticStudio.eventStudio; * * public class Foo{ * void doSomethingAndNotify(){ * ..... * eventStudio.broadcast(new ImFinished(), "station"); * } * } * } * </pre> * <p> * <b>Hidden Station</b>: The hidden station is a pre-built station with <em>"hidden.station"</em> name that is used to hide the station abstraction. Helper method are provided by * {@link DefaultEventStudio} where the station name parameter is missing from the parameters list and the {@link DefaultEventStudio#HIDDEN_STATION} is used, providing a more * traditional event bus pub/sub pattern. * </p> * * @author Andrea Vacondio * */ public class DefaultEventStudio implements EventStudio { /** * A reserved station name that is used to hide the station abstraction. Using the provided helper methods the station concept remains totally hidden and {@link EventStudio} * can be used as a more traditional Event Bus with pub/sub pattern. */ public static final String HIDDEN_STATION = "hidden.station"; private Stations stations = new Stations(); public <T> void add(Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(listener, priority, strength); } public <T> void add(Listener<T> listener, String station) { add(listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station) { add(eventClass, listener, station, 0, ReferenceStrength.STRONG); } public <T> void add(Class<T> eventClass, Listener<T> listener, String station, int priority, ReferenceStrength strength) { stations.getStation(station).add(eventClass, listener, priority, strength); } public void addAnnotatedListeners(Object bean) { try { ReflectiveMetadata metadata = Annotations.process(bean); for (Entry<String, List<ReflectiveListenerDescriptor>> current : metadata.getDescriptors().entrySet()) { String station = defaultString(metadata.getStation(), HIDDEN_STATION); stations.getStation(defaultString(current.getKey(), station)).addAll(bean, current.getValue()); } } catch (IllegalAccessException | InvocationTargetException e) {
throw new EventStudioException("An error occurred processing the input bean", e);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException;
* Adds a {@link Listener} to the hidden station, hiding the station abstraction. * * @see EventStudio#add(Listener, String) * @see DefaultEventStudio#HIDDEN_STATION */ public <T> void add(Listener<T> listener) { add(listener, HIDDEN_STATION); } /** * Adds a {@link Listener} to the hidden station listening for the given event class, hiding the station abstraction. * * @see EventStudio#add(Class, Listener, String) * @see DefaultEventStudio#HIDDEN_STATION */ public <T> void add(Class<T> eventClass, Listener<T> listener) { add(eventClass, listener, HIDDEN_STATION); } /** * Adds a {@link Supervisor} to the hidden station, hiding the station abstraction. * * @see EventStudio#supervisor(Supervisor, String) * @see DefaultEventStudio#HIDDEN_STATION */ public void supervisor(Supervisor supervisor) { supervisor(supervisor, HIDDEN_STATION); } public void supervisor(Supervisor supervisor, String station) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/util/StringUtils.java // public static String defaultString(String input, String defaultValue) { // return StringUtils.isBlank(input) ? defaultValue : input; // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/DefaultEventStudio.java import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import static org.pdfsam.eventstudio.util.StringUtils.defaultString; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map.Entry; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.exception.EventStudioException; * Adds a {@link Listener} to the hidden station, hiding the station abstraction. * * @see EventStudio#add(Listener, String) * @see DefaultEventStudio#HIDDEN_STATION */ public <T> void add(Listener<T> listener) { add(listener, HIDDEN_STATION); } /** * Adds a {@link Listener} to the hidden station listening for the given event class, hiding the station abstraction. * * @see EventStudio#add(Class, Listener, String) * @see DefaultEventStudio#HIDDEN_STATION */ public <T> void add(Class<T> eventClass, Listener<T> listener) { add(eventClass, listener, HIDDEN_STATION); } /** * Adds a {@link Supervisor} to the hidden station, hiding the station abstraction. * * @see EventStudio#supervisor(Supervisor, String) * @see DefaultEventStudio#HIDDEN_STATION */ public void supervisor(Supervisor supervisor) { supervisor(supervisor, HIDDEN_STATION); } public void supervisor(Supervisor supervisor, String station) {
requireNotNull(supervisor);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/EntityTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class ReferencedEntity<T> implements Entity<T> { // private final Reference<T> reference; // // ReferencedEntity(Reference<T> reference) { // requireNotNull(reference); // this.reference = reference; // } // // public T get() { // return reference.get(); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class StrongEntity<T> implements Entity<T> { // private final T referent; // // StrongEntity(T referent) { // this.referent = referent; // } // // public T get() { // return referent; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.ref.SoftReference; import org.junit.Test; import org.pdfsam.eventstudio.Entity.ReferencedEntity; import org.pdfsam.eventstudio.Entity.StrongEntity;
/* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class EntityTest { @Test public void testNull() {
// Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class ReferencedEntity<T> implements Entity<T> { // private final Reference<T> reference; // // ReferencedEntity(Reference<T> reference) { // requireNotNull(reference); // this.reference = reference; // } // // public T get() { // return reference.get(); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class StrongEntity<T> implements Entity<T> { // private final T referent; // // StrongEntity(T referent) { // this.referent = referent; // } // // public T get() { // return referent; // } // // } // Path: src/test/java/org/pdfsam/eventstudio/EntityTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.ref.SoftReference; import org.junit.Test; import org.pdfsam.eventstudio.Entity.ReferencedEntity; import org.pdfsam.eventstudio.Entity.StrongEntity; /* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class EntityTest { @Test public void testNull() {
Entity<Object> victim = new StrongEntity<>(null);
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/EntityTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class ReferencedEntity<T> implements Entity<T> { // private final Reference<T> reference; // // ReferencedEntity(Reference<T> reference) { // requireNotNull(reference); // this.reference = reference; // } // // public T get() { // return reference.get(); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class StrongEntity<T> implements Entity<T> { // private final T referent; // // StrongEntity(T referent) { // this.referent = referent; // } // // public T get() { // return referent; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.ref.SoftReference; import org.junit.Test; import org.pdfsam.eventstudio.Entity.ReferencedEntity; import org.pdfsam.eventstudio.Entity.StrongEntity;
/* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class EntityTest { @Test public void testNull() { Entity<Object> victim = new StrongEntity<>(null); assertNull(victim.get()); } @Test public void testStrong() { Object referent = new Object(); Entity<Object> victim = new StrongEntity<>(referent); assertEquals(referent, victim.get()); } @Test public void testReference() { Object referent = new Object();
// Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class ReferencedEntity<T> implements Entity<T> { // private final Reference<T> reference; // // ReferencedEntity(Reference<T> reference) { // requireNotNull(reference); // this.reference = reference; // } // // public T get() { // return reference.get(); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Entity.java // class StrongEntity<T> implements Entity<T> { // private final T referent; // // StrongEntity(T referent) { // this.referent = referent; // } // // public T get() { // return referent; // } // // } // Path: src/test/java/org/pdfsam/eventstudio/EntityTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.ref.SoftReference; import org.junit.Test; import org.pdfsam.eventstudio.Entity.ReferencedEntity; import org.pdfsam.eventstudio.Entity.StrongEntity; /* * This file is part of the EventStudio source code * Created on 14/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class EntityTest { @Test public void testNull() { Entity<Object> victim = new StrongEntity<>(null); assertNull(victim.get()); } @Test public void testStrong() { Object referent = new Object(); Entity<Object> victim = new StrongEntity<>(referent); assertEquals(referent, victim.get()); } @Test public void testReference() { Object referent = new Object();
Entity<Object> victim = new ReferencedEntity<>(new SoftReference<>(referent));
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 16/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class AnnotationsTest { @Test public void stationField() throws IllegalAccessException, InvocationTargetException {
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 16/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class AnnotationsTest { @Test public void stationField() throws IllegalAccessException, InvocationTargetException {
ReflectiveMetadata metadata = Annotations.process(new StationField());
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException;
/* * This file is part of the EventStudio source code * Created on 16/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class AnnotationsTest { @Test public void stationField() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationField()); assertEquals("StationField", metadata.getStation()); assertEquals(1, metadata.getDescriptors().size()); } @Test public void stationFieldEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationFieldEnum()); assertEquals("CHUCK", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); } @Test public void stationMethod() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethod()); assertEquals("myStation", metadata.getStation()); assertEquals(2, metadata.getDescriptors().get("").size()); } @Test public void stationMethodEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethodEnum()); assertEquals("NORRIS", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); }
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; /* * This file is part of the EventStudio source code * Created on 16/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * @author Andrea Vacondio * */ public class AnnotationsTest { @Test public void stationField() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationField()); assertEquals("StationField", metadata.getStation()); assertEquals(1, metadata.getDescriptors().size()); } @Test public void stationFieldEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationFieldEnum()); assertEquals("CHUCK", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); } @Test public void stationMethod() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethod()); assertEquals("myStation", metadata.getStation()); assertEquals(2, metadata.getDescriptors().get("").size()); } @Test public void stationMethodEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethodEnum()); assertEquals("NORRIS", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); }
@Test(expected = EventStudioException.class)
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException;
assertEquals("myStation", metadata.getStation()); assertEquals(2, metadata.getDescriptors().get("").size()); } @Test public void stationMethodEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethodEnum()); assertEquals("NORRIS", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); } @Test(expected = EventStudioException.class) public void wrongListener() throws IllegalAccessException, InvocationTargetException { Annotations.process(new WrongListener()); } @Test(expected = EventStudioException.class) public void wrongStation() throws IllegalAccessException, InvocationTargetException { Annotations.process(new WrongStation()); } @Test public void listenerWithStation() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new ListenerWithStation()); assertEquals(1, metadata.getDescriptors().get("MyPersonalStation").size()); } @Test public void inheritedListeners() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new ChildListener());
// Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveMetadata { // private String station; // private final Map<String, List<ReflectiveListenerDescriptor>> descriptors = new HashMap<>(); // // private void put(String station, ReflectiveListenerDescriptor descriptor) { // List<ReflectiveListenerDescriptor> current = descriptors.computeIfAbsent(station, k -> new ArrayList<>()); // current.add(descriptor); // } // // public String getStation() { // return station; // } // // public Map<String, List<ReflectiveListenerDescriptor>> getDescriptors() { // return descriptors; // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/org/pdfsam/eventstudio/AnnotationsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.junit.Test; import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.Annotations.ReflectiveMetadata; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; import org.pdfsam.eventstudio.exception.EventStudioException; assertEquals("myStation", metadata.getStation()); assertEquals(2, metadata.getDescriptors().get("").size()); } @Test public void stationMethodEnum() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new StationMethodEnum()); assertEquals("NORRIS", metadata.getStation()); assertEquals(0, metadata.getDescriptors().size()); } @Test(expected = EventStudioException.class) public void wrongListener() throws IllegalAccessException, InvocationTargetException { Annotations.process(new WrongListener()); } @Test(expected = EventStudioException.class) public void wrongStation() throws IllegalAccessException, InvocationTargetException { Annotations.process(new WrongStation()); } @Test public void listenerWithStation() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new ListenerWithStation()); assertEquals(1, metadata.getDescriptors().get("MyPersonalStation").size()); } @Test public void inheritedListeners() throws IllegalAccessException, InvocationTargetException { ReflectiveMetadata metadata = Annotations.process(new ChildListener());
List<ReflectiveListenerDescriptor> parentStation = metadata.getDescriptors().get("parentStation");
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/shakedown/AnotherAnnotatedListener.java
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // }
import java.util.Random; import org.pdfsam.eventstudio.ReferenceStrength; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation;
/* * This file is part of the EventStudio source code * Created on 20/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.shakedown; /** * @author Andrea Vacondio * */ public class AnotherAnnotatedListener { @EventStation private static final String STATION = "station"; @EventListener public void listener(MyEvent event) { System.out.println(new Random().nextInt()); }
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // } // Path: src/test/java/org/pdfsam/eventstudio/shakedown/AnotherAnnotatedListener.java import java.util.Random; import org.pdfsam.eventstudio.ReferenceStrength; import org.pdfsam.eventstudio.annotation.EventListener; import org.pdfsam.eventstudio.annotation.EventStation; /* * This file is part of the EventStudio source code * Created on 20/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.shakedown; /** * @author Andrea Vacondio * */ public class AnotherAnnotatedListener { @EventStation private static final String STATION = "station"; @EventListener public void listener(MyEvent event) { System.out.println(new Random().nextInt()); }
@EventListener(station = "anotherStation", priority = 2, strength = ReferenceStrength.SOFT)
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/annotation/EventListener.java
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.pdfsam.eventstudio.ReferenceStrength;
/* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.annotation; /** * Annotated methods will be registered as Listener for the event in the method signature. Method signature must have a single parameter from which the event class will be * inferred. Multiple methods on the same pojo can be annotated. * * @author Andrea Vacondio * */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface EventListener { /** * @return the priority for this listener, low numbers mean high priority. */ int priority() default 0; /** * @return the station for this listener. If nothing is specified the {@link EventStation} annotated field or method will be used. */ String station() default ""; /** * @return the reference strength for this listener. */
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // } // Path: src/main/java/org/pdfsam/eventstudio/annotation/EventListener.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.pdfsam.eventstudio.ReferenceStrength; /* * This file is part of the EventStudio source code * Created on 15/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.annotation; /** * Annotated methods will be registered as Listener for the event in the method signature. Method signature must have a single parameter from which the event class will be * inferred. Multiple methods on the same pojo can be annotated. * * @author Andrea Vacondio * */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface EventListener { /** * @return the priority for this listener, low numbers mean high priority. */ int priority() default 0; /** * @return the station for this listener. If nothing is specified the {@link EventStation} annotated field or method will be used. */ String station() default ""; /** * @return the reference strength for this listener. */
ReferenceStrength strength() default ReferenceStrength.STRONG;
torakiki/event-studio
src/test/java/org/pdfsam/eventstudio/shakedown/AnnotatedTestListener.java
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // }
import java.util.Random; import org.pdfsam.eventstudio.ReferenceStrength; import org.pdfsam.eventstudio.annotation.EventListener;
/* * This file is part of the EventStudio source code * Created on 20/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.shakedown; /** * @author Andrea Vacondio * */ public class AnnotatedTestListener { @EventListener(priority = 1) public void first(AnotherMyEvent event) { System.out.println(new Random().nextInt()); }
// Path: src/main/java/org/pdfsam/eventstudio/ReferenceStrength.java // public enum ReferenceStrength { // STRONG { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.StrongEntity<>(referent); // } // }, // SOFT { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new SoftReference<>(referent)); // } // }, // WEAK { // @Override // <T> Entity<T> getReference(T referent) { // return new Entity.ReferencedEntity<>(new WeakReference<>(referent)); // } // }; // // /** // * @return the referent wrapped with the appropriate {@link Entity} instance. // */ // abstract <T> Entity<T> getReference(T referent); // } // Path: src/test/java/org/pdfsam/eventstudio/shakedown/AnnotatedTestListener.java import java.util.Random; import org.pdfsam.eventstudio.ReferenceStrength; import org.pdfsam.eventstudio.annotation.EventListener; /* * This file is part of the EventStudio source code * Created on 20/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio.shakedown; /** * @author Andrea Vacondio * */ public class AnnotatedTestListener { @EventListener(priority = 1) public void first(AnotherMyEvent event) { System.out.println(new Random().nextInt()); }
@EventListener(priority = 2, strength = ReferenceStrength.WEAK)
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Listeners.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock;
/* * This file is part of the EventStudio source code * Created on 11/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * A thread-safe holder for the listeners * * @author Andrea Vacondio */ class Listeners { private static final Logger LOG = LoggerFactory.getLogger(Listeners.class); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final Map<Class<?>, TreeSet<ListenerReferenceHolder>> listeners = new HashMap<>(); <T> void add(Class<T> eventClass, Listener<T> listener, int priority, ReferenceStrength strength) { lock.writeLock().lock(); try { TreeSet<ListenerReferenceHolder> set = nullSafeGetListenerHolders(eventClass); set.add(new ListenerReferenceHolder(priority, strength.getReference(new DefaultListenerWrapper(listener)))); } finally { lock.writeLock().unlock(); } }
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock; /* * This file is part of the EventStudio source code * Created on 11/nov/2013 * Copyright 2020 by Sober Lemur S.a.s di Vacondio Andrea (info@pdfsam.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pdfsam.eventstudio; /** * A thread-safe holder for the listeners * * @author Andrea Vacondio */ class Listeners { private static final Logger LOG = LoggerFactory.getLogger(Listeners.class); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final Map<Class<?>, TreeSet<ListenerReferenceHolder>> listeners = new HashMap<>(); <T> void add(Class<T> eventClass, Listener<T> listener, int priority, ReferenceStrength strength) { lock.writeLock().lock(); try { TreeSet<ListenerReferenceHolder> set = nullSafeGetListenerHolders(eventClass); set.add(new ListenerReferenceHolder(priority, strength.getReference(new DefaultListenerWrapper(listener)))); } finally { lock.writeLock().unlock(); } }
public Set<Class<?>> addAll(Object bean, List<ReflectiveListenerDescriptor> descriptors) {
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Listeners.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock;
TreeSet<ListenerReferenceHolder> set = listeners.get(eventClass); if (set != null) { lock.readLock().unlock(); lock.writeLock().lock(); try { return removeListenerAndSetIfNeeded(eventClass, listener, set); } finally { lock.writeLock().unlock(); } } lock.readLock().unlock(); return false; } private boolean removeListenerAndSetIfNeeded(Class<?> eventClass, ListenerReferenceHolder listener, TreeSet<ListenerReferenceHolder> set) { if (set.remove(listener)) { if (set.isEmpty()) { listeners.remove(eventClass); LOG.trace("Removed empty listeners set for {}", eventClass); } return true; } return false; } /** * @return A sorted set containing the listeners queue for the given class. */ List<ListenerReferenceHolder> nullSafeGetListeners(Class<?> eventClass) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock; TreeSet<ListenerReferenceHolder> set = listeners.get(eventClass); if (set != null) { lock.readLock().unlock(); lock.writeLock().lock(); try { return removeListenerAndSetIfNeeded(eventClass, listener, set); } finally { lock.writeLock().unlock(); } } lock.readLock().unlock(); return false; } private boolean removeListenerAndSetIfNeeded(Class<?> eventClass, ListenerReferenceHolder listener, TreeSet<ListenerReferenceHolder> set) { if (set.remove(listener)) { if (set.isEmpty()) { listeners.remove(eventClass); LOG.trace("Removed empty listeners set for {}", eventClass); } return true; } return false; } /** * @return A sorted set containing the listeners queue for the given class. */ List<ListenerReferenceHolder> nullSafeGetListeners(Class<?> eventClass) {
requireNotNull(eventClass);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Listeners.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock;
if (this == o) { return true; } if (!(o instanceof DefaultListenerWrapper)) { return false; } DefaultListenerWrapper other = (DefaultListenerWrapper) o; return wrapped.equals(other.wrapped); } } /** * Reflective invocation of an annotated listener * * @author Andrea Vacondio */ private static final class ReflectiveListenerWrapper implements ListenerWrapper { private final Object bean; private final Method method; public ReflectiveListenerWrapper(Object bean, Method method) { this.bean = bean; this.method = method; this.method.setAccessible(true); } public void onEvent(Envelope event) { try { method.invoke(bean, event.getEvent()); } catch (IllegalAccessException e) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock; if (this == o) { return true; } if (!(o instanceof DefaultListenerWrapper)) { return false; } DefaultListenerWrapper other = (DefaultListenerWrapper) o; return wrapped.equals(other.wrapped); } } /** * Reflective invocation of an annotated listener * * @author Andrea Vacondio */ private static final class ReflectiveListenerWrapper implements ListenerWrapper { private final Object bean; private final Method method; public ReflectiveListenerWrapper(Object bean, Method method) { this.bean = bean; this.method = method; this.method.setAccessible(true); } public void onEvent(Envelope event) { try { method.invoke(bean, event.getEvent()); } catch (IllegalAccessException e) {
throw new EventStudioException("Exception invoking reflective method", e);
torakiki/event-studio
src/main/java/org/pdfsam/eventstudio/Listeners.java
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // }
import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock;
} if (!(o instanceof DefaultListenerWrapper)) { return false; } DefaultListenerWrapper other = (DefaultListenerWrapper) o; return wrapped.equals(other.wrapped); } } /** * Reflective invocation of an annotated listener * * @author Andrea Vacondio */ private static final class ReflectiveListenerWrapper implements ListenerWrapper { private final Object bean; private final Method method; public ReflectiveListenerWrapper(Object bean, Method method) { this.bean = bean; this.method = method; this.method.setAccessible(true); } public void onEvent(Envelope event) { try { method.invoke(bean, event.getEvent()); } catch (IllegalAccessException e) { throw new EventStudioException("Exception invoking reflective method", e); } catch (InvocationTargetException e) {
// Path: src/main/java/org/pdfsam/eventstudio/util/RequireUtils.java // public static void requireNotNull(Object victim) { // if (victim == null) { // throw new IllegalArgumentException("The input object cannot be null"); // } // } // // Path: src/main/java/org/pdfsam/eventstudio/Annotations.java // static class ReflectiveListenerDescriptor { // // private final EventListener listenerAnnotation; // private final Method method; // // public ReflectiveListenerDescriptor(EventListener listenerAnnotation, Method method) { // this.listenerAnnotation = listenerAnnotation; // this.method = method; // } // // public EventListener getListenerAnnotation() { // return listenerAnnotation; // } // // public Method getMethod() { // return method; // } // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/BroadcastInterruptionException.java // public class BroadcastInterruptionException extends EventStudioException { // // public BroadcastInterruptionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/pdfsam/eventstudio/exception/EventStudioException.java // public class EventStudioException extends RuntimeException { // // public EventStudioException(String message, Throwable cause) { // super(message, cause); // } // // public EventStudioException(String message) { // super(message); // } // // public EventStudioException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/org/pdfsam/eventstudio/Listeners.java import org.pdfsam.eventstudio.Annotations.ReflectiveListenerDescriptor; import org.pdfsam.eventstudio.exception.BroadcastInterruptionException; import org.pdfsam.eventstudio.exception.EventStudioException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.pdfsam.eventstudio.util.RequireUtils.requireNotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantReadWriteLock; } if (!(o instanceof DefaultListenerWrapper)) { return false; } DefaultListenerWrapper other = (DefaultListenerWrapper) o; return wrapped.equals(other.wrapped); } } /** * Reflective invocation of an annotated listener * * @author Andrea Vacondio */ private static final class ReflectiveListenerWrapper implements ListenerWrapper { private final Object bean; private final Method method; public ReflectiveListenerWrapper(Object bean, Method method) { this.bean = bean; this.method = method; this.method.setAccessible(true); } public void onEvent(Envelope event) { try { method.invoke(bean, event.getEvent()); } catch (IllegalAccessException e) { throw new EventStudioException("Exception invoking reflective method", e); } catch (InvocationTargetException e) {
if (e.getCause() instanceof BroadcastInterruptionException) {
ddcap/halvade
halvade/src/be/ugent/intec/halvade/hadoop/partitioners/ChrRgSortComparator.java
// Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/ChromosomeRegion.java // public class ChromosomeRegion implements WritableComparable<ChromosomeRegion> { // protected int chromosome; // protected int position; // protected int reduceNumber; // identifies region in chromosome but every number is unique, so chr is also separate! // // public int getChromosome() { // return chromosome; // } // // public int getPosition() { // return position; // } // // public int getReduceNumber() { // return reduceNumber; // } // // public void setChromosomeRegion(int chromosome, int position, int reducenumber) { // this.chromosome = chromosome; // this.position = position; // this.reduceNumber = reducenumber; // } // // public ChromosomeRegion() { // this.reduceNumber = -1; // this.chromosome = -1; // this.position = -1; // } // // @Override // public void write(DataOutput d) throws IOException { // d.writeInt(chromosome); // d.writeInt(position); // d.writeInt(reduceNumber); // } // // @Override // public void readFields(DataInput di) throws IOException { // chromosome = di.readInt(); // position = di.readInt(); // reduceNumber = di.readInt(); // } // // @Override // public int compareTo(ChromosomeRegion t) { // /* // * returns: // * x < 0 if t is less than this // * 0 if equals // * x > 0 if t is bigger than this // */ // // if(chromosome == t.chromosome) { // if(reduceNumber == t.reduceNumber) // return position - t.position; // else // return reduceNumber - t.reduceNumber; // // } else // // return chromosome - t.chromosome; // } // // @Override // public String toString() { // return "region_" + reduceNumber; // } // public String toFullString() { // return chromosome + "-" + reduceNumber + "-" + position; // } // }
import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator;
/* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.hadoop.partitioners; /** * * @author ddecap */ public class ChrRgSortComparator extends WritableComparator { protected ChrRgSortComparator() {
// Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/ChromosomeRegion.java // public class ChromosomeRegion implements WritableComparable<ChromosomeRegion> { // protected int chromosome; // protected int position; // protected int reduceNumber; // identifies region in chromosome but every number is unique, so chr is also separate! // // public int getChromosome() { // return chromosome; // } // // public int getPosition() { // return position; // } // // public int getReduceNumber() { // return reduceNumber; // } // // public void setChromosomeRegion(int chromosome, int position, int reducenumber) { // this.chromosome = chromosome; // this.position = position; // this.reduceNumber = reducenumber; // } // // public ChromosomeRegion() { // this.reduceNumber = -1; // this.chromosome = -1; // this.position = -1; // } // // @Override // public void write(DataOutput d) throws IOException { // d.writeInt(chromosome); // d.writeInt(position); // d.writeInt(reduceNumber); // } // // @Override // public void readFields(DataInput di) throws IOException { // chromosome = di.readInt(); // position = di.readInt(); // reduceNumber = di.readInt(); // } // // @Override // public int compareTo(ChromosomeRegion t) { // /* // * returns: // * x < 0 if t is less than this // * 0 if equals // * x > 0 if t is bigger than this // */ // // if(chromosome == t.chromosome) { // if(reduceNumber == t.reduceNumber) // return position - t.position; // else // return reduceNumber - t.reduceNumber; // // } else // // return chromosome - t.chromosome; // } // // @Override // public String toString() { // return "region_" + reduceNumber; // } // public String toFullString() { // return chromosome + "-" + reduceNumber + "-" + position; // } // } // Path: halvade/src/be/ugent/intec/halvade/hadoop/partitioners/ChrRgSortComparator.java import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; /* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.hadoop.partitioners; /** * * @author ddecap */ public class ChrRgSortComparator extends WritableComparator { protected ChrRgSortComparator() {
super(ChromosomeRegion.class, true);
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/BaseInterleaveFiles.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java // public class FileReaderFactory extends BaseFileReader implements Runnable { // protected ArrayList<BaseFileReader> readers; // protected BaseFileReader currentReader = null; // protected static FileReaderFactory allReaders = null; // protected int threads; // protected boolean fromHDFS = false; // // public FileReaderFactory(int threads, boolean fromHDFS) { // super(false); // readers = new ArrayList<>(); // this.threads = threads; // this.fromHDFS = fromHDFS; // } // // public static FileReaderFactory getInstance(int threads, boolean fromHDFS) { // if(allReaders == null) { // allReaders = new FileReaderFactory(threads, fromHDFS); // } // return allReaders; // } // // public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { // if (fileB == null) { // return new SingleFastQReader(fromHDFS, fileA, interleaved); // } else { // return new PairedFastQReader(fromHDFS, fileA, fileB); // } // } // // public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { // readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); // } // // public void addReader(BaseFileReader reader) { // readers.add(reader); // } // // // public ReadBlock retrieveBlock() { // try { // ReadBlock block = null; // while((check || blocks.size() > 0) && block == null) { // block = blocks.poll(1000, TimeUnit.MILLISECONDS); // } // return block; // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // return null; // } // } // // // @Override // protected int addNextRead(ReadBlock block) throws IOException { // return currentReader.addNextRead(block); // } // // protected synchronized boolean getNextReader() { // if(currentReader == null) { // if(readers.size() > 0) { // currentReader = readers.remove(readers.size() - 1); // Logger.DEBUG("Reader: " + currentReader); // return true; // } else { // Logger.DEBUG("Processed all readers"); // return false; // } // } else return true; // } // // // protected boolean check = true; // protected ArrayBlockingQueue<ReadBlock> blocks; // protected int READ_BLOCK_CAPACITY_PER_THREAD = 10; // // @Override // public void run() { // blocks = new ArrayBlockingQueue<>(READ_BLOCK_CAPACITY_PER_THREAD*threads); // if(currentReader == null) { // if(!getNextReader()) check = false; // } // try { // while(check) { // ReadBlock block = new ReadBlock(); // boolean hasReads = super.getNextBlock(block); // if (!hasReads) { // currentReader = null; // if(!getNextReader()) // check = false; // } else { // blocks.put(block); // } // } // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // } // } // }
import be.ugent.intec.halvade.uploader.input.ReadBlock; import be.ugent.intec.halvade.uploader.input.FileReaderFactory; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream;
/* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.uploader; /** * * @author ddecap */ abstract class BaseInterleaveFiles extends Thread { protected static final int BUFFERSIZE = 8*1024; protected static long maxFileSize; // ~60MB
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java // public class FileReaderFactory extends BaseFileReader implements Runnable { // protected ArrayList<BaseFileReader> readers; // protected BaseFileReader currentReader = null; // protected static FileReaderFactory allReaders = null; // protected int threads; // protected boolean fromHDFS = false; // // public FileReaderFactory(int threads, boolean fromHDFS) { // super(false); // readers = new ArrayList<>(); // this.threads = threads; // this.fromHDFS = fromHDFS; // } // // public static FileReaderFactory getInstance(int threads, boolean fromHDFS) { // if(allReaders == null) { // allReaders = new FileReaderFactory(threads, fromHDFS); // } // return allReaders; // } // // public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { // if (fileB == null) { // return new SingleFastQReader(fromHDFS, fileA, interleaved); // } else { // return new PairedFastQReader(fromHDFS, fileA, fileB); // } // } // // public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { // readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); // } // // public void addReader(BaseFileReader reader) { // readers.add(reader); // } // // // public ReadBlock retrieveBlock() { // try { // ReadBlock block = null; // while((check || blocks.size() > 0) && block == null) { // block = blocks.poll(1000, TimeUnit.MILLISECONDS); // } // return block; // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // return null; // } // } // // // @Override // protected int addNextRead(ReadBlock block) throws IOException { // return currentReader.addNextRead(block); // } // // protected synchronized boolean getNextReader() { // if(currentReader == null) { // if(readers.size() > 0) { // currentReader = readers.remove(readers.size() - 1); // Logger.DEBUG("Reader: " + currentReader); // return true; // } else { // Logger.DEBUG("Processed all readers"); // return false; // } // } else return true; // } // // // protected boolean check = true; // protected ArrayBlockingQueue<ReadBlock> blocks; // protected int READ_BLOCK_CAPACITY_PER_THREAD = 10; // // @Override // public void run() { // blocks = new ArrayBlockingQueue<>(READ_BLOCK_CAPACITY_PER_THREAD*threads); // if(currentReader == null) { // if(!getNextReader()) check = false; // } // try { // while(check) { // ReadBlock block = new ReadBlock(); // boolean hasReads = super.getNextBlock(block); // if (!hasReads) { // currentReader = null; // if(!getNextReader()) // check = false; // } else { // blocks.put(block); // } // } // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // } // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/BaseInterleaveFiles.java import be.ugent.intec.halvade.uploader.input.ReadBlock; import be.ugent.intec.halvade.uploader.input.FileReaderFactory; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; /* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.uploader; /** * * @author ddecap */ abstract class BaseInterleaveFiles extends Thread { protected static final int BUFFERSIZE = 8*1024; protected static long maxFileSize; // ~60MB
protected FileReaderFactory factory;
ddcap/halvade
halvade/src/be/ugent/intec/halvade/utils/SAMRecordIterator.java
// Path: halvade/src/be/ugent/intec/halvade/tools/QualityException.java // public class QualityException extends Exception { // private boolean illegal = false; // private byte errorCode; // // QualityException(byte error) { // super(); // errorCode = error; // } // // QualityException() { // super(); // illegal = true; // } // // @Override // public String toString() { // if(illegal) // return "Illegal Phred 64 or Phred 33 encoding"; // else // return "Error converting Phred 64 to Phred 33 quality : " + (int)errorCode; // } // }
import be.ugent.intec.halvade.tools.QualityEncoding; import be.ugent.intec.halvade.tools.QualityException; import org.seqdoop.hadoop_bam.SAMRecordWritable; import java.util.Iterator; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.utils; /** * * @author ddecap */ public class SAMRecordIterator implements Iterator<SAMRecord> { protected Iterator<SAMRecordWritable> it; protected ChromosomeRange r; protected SAMRecord sam = null; protected int reads = 0; protected int currentStart = -1, currentEnd = -1, currentChr = -1; protected String chrString = ""; protected boolean requireFixQuality = false; protected SAMFileHeader header; protected static final int INTERVAL_OVERLAP = 51;
// Path: halvade/src/be/ugent/intec/halvade/tools/QualityException.java // public class QualityException extends Exception { // private boolean illegal = false; // private byte errorCode; // // QualityException(byte error) { // super(); // errorCode = error; // } // // QualityException() { // super(); // illegal = true; // } // // @Override // public String toString() { // if(illegal) // return "Illegal Phred 64 or Phred 33 encoding"; // else // return "Error converting Phred 64 to Phred 33 quality : " + (int)errorCode; // } // } // Path: halvade/src/be/ugent/intec/halvade/utils/SAMRecordIterator.java import be.ugent.intec.halvade.tools.QualityEncoding; import be.ugent.intec.halvade.tools.QualityException; import org.seqdoop.hadoop_bam.SAMRecordWritable; import java.util.Iterator; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.utils; /** * * @author ddecap */ public class SAMRecordIterator implements Iterator<SAMRecord> { protected Iterator<SAMRecordWritable> it; protected ChromosomeRange r; protected SAMRecord sam = null; protected int reads = 0; protected int currentStart = -1, currentEnd = -1, currentChr = -1; protected String chrString = ""; protected boolean requireFixQuality = false; protected SAMFileHeader header; protected static final int INTERVAL_OVERLAP = 51;
public SAMRecordIterator(Iterator<SAMRecordWritable> it, SAMFileHeader header, boolean requireFixQuality) throws QualityException {
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java // protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException { // InputStream hdfsIn; // if(readFromDistributedStorage) { // Path pt =new Path(file); // FileSystem fs = FileSystem.get(pt.toUri(), new Configuration()); // hdfsIn = fs.open(pt); // // read the stream in the correct format! // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn); // return new BufferedReader(new InputStreamReader(bzip2)); // } else // return new BufferedReader(new InputStreamReader(hdfsIn)); // // } else { // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file)); // return new BufferedReader(new InputStreamReader(bzip2)); // } else if(file.equals("-")) { // return new BufferedReader(new InputStreamReader(System.in)); // }else // return new BufferedReader(new FileReader(file)); // } // }
import be.ugent.intec.halvade.uploader.Logger; import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader; import java.io.BufferedReader; import java.io.IOException;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class SingleFastQReader extends BaseFileReader { protected BufferedReader readerA; protected ReadBlock block; protected int readsFactor; public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException { super(true);
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java // protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException { // InputStream hdfsIn; // if(readFromDistributedStorage) { // Path pt =new Path(file); // FileSystem fs = FileSystem.get(pt.toUri(), new Configuration()); // hdfsIn = fs.open(pt); // // read the stream in the correct format! // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn); // return new BufferedReader(new InputStreamReader(bzip2)); // } else // return new BufferedReader(new InputStreamReader(hdfsIn)); // // } else { // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file)); // return new BufferedReader(new InputStreamReader(bzip2)); // } else if(file.equals("-")) { // return new BufferedReader(new InputStreamReader(System.in)); // }else // return new BufferedReader(new FileReader(file)); // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java import be.ugent.intec.halvade.uploader.Logger; import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader; import java.io.BufferedReader; import java.io.IOException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class SingleFastQReader extends BaseFileReader { protected BufferedReader readerA; protected ReadBlock block; protected int readsFactor; public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException { super(true);
readerA = getReader(fromHDFS, fileA);
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java // protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException { // InputStream hdfsIn; // if(readFromDistributedStorage) { // Path pt =new Path(file); // FileSystem fs = FileSystem.get(pt.toUri(), new Configuration()); // hdfsIn = fs.open(pt); // // read the stream in the correct format! // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn); // return new BufferedReader(new InputStreamReader(bzip2)); // } else // return new BufferedReader(new InputStreamReader(hdfsIn)); // // } else { // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file)); // return new BufferedReader(new InputStreamReader(bzip2)); // } else if(file.equals("-")) { // return new BufferedReader(new InputStreamReader(System.in)); // }else // return new BufferedReader(new FileReader(file)); // } // }
import be.ugent.intec.halvade.uploader.Logger; import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader; import java.io.BufferedReader; import java.io.IOException;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class SingleFastQReader extends BaseFileReader { protected BufferedReader readerA; protected ReadBlock block; protected int readsFactor; public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException { super(true); readerA = getReader(fromHDFS, fileA); this.isInterleaved = interleaved; if(isInterleaved) readsFactor = 2; else readsFactor = 1; toStr = fileA;
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java // protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException { // InputStream hdfsIn; // if(readFromDistributedStorage) { // Path pt =new Path(file); // FileSystem fs = FileSystem.get(pt.toUri(), new Configuration()); // hdfsIn = fs.open(pt); // // read the stream in the correct format! // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn); // return new BufferedReader(new InputStreamReader(bzip2)); // } else // return new BufferedReader(new InputStreamReader(hdfsIn)); // // } else { // if(file.endsWith(".gz")) { // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE); // return new BufferedReader(new InputStreamReader(gzip)); // } else if(file.endsWith(".bz2")) { // CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file)); // return new BufferedReader(new InputStreamReader(bzip2)); // } else if(file.equals("-")) { // return new BufferedReader(new InputStreamReader(System.in)); // }else // return new BufferedReader(new FileReader(file)); // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java import be.ugent.intec.halvade.uploader.Logger; import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader; import java.io.BufferedReader; import java.io.IOException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class SingleFastQReader extends BaseFileReader { protected BufferedReader readerA; protected ReadBlock block; protected int readsFactor; public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException { super(true); readerA = getReader(fromHDFS, fileA); this.isInterleaved = interleaved; if(isInterleaved) readsFactor = 2; else readsFactor = 1; toStr = fileA;
Logger.DEBUG("Single: " + toStr + (isInterleaved ? " interleaved" : ""));
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/HalvadeUploader.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java // public class FileReaderFactory extends BaseFileReader implements Runnable { // protected ArrayList<BaseFileReader> readers; // protected BaseFileReader currentReader = null; // protected static FileReaderFactory allReaders = null; // protected int threads; // protected boolean fromHDFS = false; // // public FileReaderFactory(int threads, boolean fromHDFS) { // super(false); // readers = new ArrayList<>(); // this.threads = threads; // this.fromHDFS = fromHDFS; // } // // public static FileReaderFactory getInstance(int threads, boolean fromHDFS) { // if(allReaders == null) { // allReaders = new FileReaderFactory(threads, fromHDFS); // } // return allReaders; // } // // public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { // if (fileB == null) { // return new SingleFastQReader(fromHDFS, fileA, interleaved); // } else { // return new PairedFastQReader(fromHDFS, fileA, fileB); // } // } // // public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { // readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); // } // // public void addReader(BaseFileReader reader) { // readers.add(reader); // } // // // public ReadBlock retrieveBlock() { // try { // ReadBlock block = null; // while((check || blocks.size() > 0) && block == null) { // block = blocks.poll(1000, TimeUnit.MILLISECONDS); // } // return block; // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // return null; // } // } // // // @Override // protected int addNextRead(ReadBlock block) throws IOException { // return currentReader.addNextRead(block); // } // // protected synchronized boolean getNextReader() { // if(currentReader == null) { // if(readers.size() > 0) { // currentReader = readers.remove(readers.size() - 1); // Logger.DEBUG("Reader: " + currentReader); // return true; // } else { // Logger.DEBUG("Processed all readers"); // return false; // } // } else return true; // } // // // protected boolean check = true; // protected ArrayBlockingQueue<ReadBlock> blocks; // protected int READ_BLOCK_CAPACITY_PER_THREAD = 10; // // @Override // public void run() { // blocks = new ArrayBlockingQueue<>(READ_BLOCK_CAPACITY_PER_THREAD*threads); // if(currentReader == null) { // if(!getNextReader()) check = false; // } // try { // while(check) { // ReadBlock block = new ReadBlock(); // boolean hasReads = super.getNextBlock(block); // if (!hasReads) { // currentReader = null; // if(!getNextReader()) // check = false; // } else { // blocks.put(block); // } // } // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // } // } // }
import be.ugent.intec.halvade.uploader.input.FileReaderFactory; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.cli.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
formatter.printHelp( "hadoop jar HalvadeUploaderWithLibs.jar -1 <MANIFEST> -O <OUT> [options]", options ); } catch (Throwable ex) { Logger.THROWABLE(ex); } return 0; } private int processFiles() throws IOException, InterruptedException, URISyntaxException, Throwable { Timer timer = new Timer(); timer.start(); AWSUploader upl = null; FileSystem fs = null; // write to s3? boolean useAWS = false; if(outputDir.startsWith("s3")) { useAWS = true; String existingBucketName = outputDir.replace("s3://","").split("/")[0]; outputDir = outputDir.replace("s3://" + existingBucketName + "/", ""); upl = new AWSUploader(existingBucketName, SSE, profile); } else { Configuration conf = getConf(); fs = FileSystem.get(new URI(outputDir), conf); Path outpath = new Path(outputDir); if (fs.exists(outpath) && !fs.getFileStatus(outpath).isDirectory()) { Logger.DEBUG("please provide an output directory"); return 1; } }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java // public class FileReaderFactory extends BaseFileReader implements Runnable { // protected ArrayList<BaseFileReader> readers; // protected BaseFileReader currentReader = null; // protected static FileReaderFactory allReaders = null; // protected int threads; // protected boolean fromHDFS = false; // // public FileReaderFactory(int threads, boolean fromHDFS) { // super(false); // readers = new ArrayList<>(); // this.threads = threads; // this.fromHDFS = fromHDFS; // } // // public static FileReaderFactory getInstance(int threads, boolean fromHDFS) { // if(allReaders == null) { // allReaders = new FileReaderFactory(threads, fromHDFS); // } // return allReaders; // } // // public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { // if (fileB == null) { // return new SingleFastQReader(fromHDFS, fileA, interleaved); // } else { // return new PairedFastQReader(fromHDFS, fileA, fileB); // } // } // // public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { // readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); // } // // public void addReader(BaseFileReader reader) { // readers.add(reader); // } // // // public ReadBlock retrieveBlock() { // try { // ReadBlock block = null; // while((check || blocks.size() > 0) && block == null) { // block = blocks.poll(1000, TimeUnit.MILLISECONDS); // } // return block; // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // return null; // } // } // // // @Override // protected int addNextRead(ReadBlock block) throws IOException { // return currentReader.addNextRead(block); // } // // protected synchronized boolean getNextReader() { // if(currentReader == null) { // if(readers.size() > 0) { // currentReader = readers.remove(readers.size() - 1); // Logger.DEBUG("Reader: " + currentReader); // return true; // } else { // Logger.DEBUG("Processed all readers"); // return false; // } // } else return true; // } // // // protected boolean check = true; // protected ArrayBlockingQueue<ReadBlock> blocks; // protected int READ_BLOCK_CAPACITY_PER_THREAD = 10; // // @Override // public void run() { // blocks = new ArrayBlockingQueue<>(READ_BLOCK_CAPACITY_PER_THREAD*threads); // if(currentReader == null) { // if(!getNextReader()) check = false; // } // try { // while(check) { // ReadBlock block = new ReadBlock(); // boolean hasReads = super.getNextBlock(block); // if (!hasReads) { // currentReader = null; // if(!getNextReader()) // check = false; // } else { // blocks.put(block); // } // } // } catch (InterruptedException ex) { // Logger.EXCEPTION(ex); // } // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/HalvadeUploader.java import be.ugent.intec.halvade.uploader.input.FileReaderFactory; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.cli.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; formatter.printHelp( "hadoop jar HalvadeUploaderWithLibs.jar -1 <MANIFEST> -O <OUT> [options]", options ); } catch (Throwable ex) { Logger.THROWABLE(ex); } return 0; } private int processFiles() throws IOException, InterruptedException, URISyntaxException, Throwable { Timer timer = new Timer(); timer.start(); AWSUploader upl = null; FileSystem fs = null; // write to s3? boolean useAWS = false; if(outputDir.startsWith("s3")) { useAWS = true; String existingBucketName = outputDir.replace("s3://","").split("/")[0]; outputDir = outputDir.replace("s3://" + existingBucketName + "/", ""); upl = new AWSUploader(existingBucketName, SSE, profile); } else { Configuration conf = getConf(); fs = FileSystem.get(new URI(outputDir), conf); Path outpath = new Path(outputDir); if (fs.exists(outpath) && !fs.getFileStatus(outpath).isDirectory()) { Logger.DEBUG("please provide an output directory"); return 1; } }
FileReaderFactory factory = FileReaderFactory.getInstance(mthreads, fromHDFS);
ddcap/halvade
halvade/src/be/ugent/intec/halvade/utils/ProcessBuilderWrapper.java
// Path: halvade/src/be/ugent/intec/halvade/tools/ProcessException.java // public class ProcessException extends InterruptedException { // private String programName; // private String[] command; // private int errorCode; // // public ProcessException(String name, int error) { // super(); // command = null; // programName = name; // errorCode = error; // } // // public ProcessException(String[] command, String name, int error) { // super(); // this.command = command; // programName = name; // errorCode = error; // } // // @Override // public String toString() { // if(command == null) // return programName + " exited with code " + errorCode; // else // return "command: " + Arrays.toString(command) + "\n" + programName + " exited with code " + errorCode; // } // // // // }
import be.ugent.intec.halvade.tools.ProcessException; import java.io.*; import java.util.Arrays;
public void startProcess(PrintStream stdout_, PrintStream stderr_) throws InterruptedException { try { Logger.DEBUG("running command " + Arrays.toString(command)); ProcessBuilder builder = new ProcessBuilder(command); if(libdir != null) { builder.environment().put( "LD_LIBRARY_PATH", "$LD_LIBRARY_PATH:" + libdir); builder.environment().put( "PYTHONPATH", "$PYTHONPATH:" + libdir); } builder.environment().put("CILK_NWORKERS", "" + threads); p = builder.start(); mon = new ProcMon(p); Thread t = new Thread(mon); t.start(); startTime = System.currentTimeMillis(); if(stdout_ != null) { this.stdout = new StreamGobbler(p.getInputStream(), stdout_); this.stdout.start(); } if(stderr_ != null) { this.stderr = new StreamGobbler(p.getErrorStream(), stderr_, "[PROCESS_ERR]"); this.stderr.start(); } stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); } catch (IOException ex) { Logger.EXCEPTION(ex);
// Path: halvade/src/be/ugent/intec/halvade/tools/ProcessException.java // public class ProcessException extends InterruptedException { // private String programName; // private String[] command; // private int errorCode; // // public ProcessException(String name, int error) { // super(); // command = null; // programName = name; // errorCode = error; // } // // public ProcessException(String[] command, String name, int error) { // super(); // this.command = command; // programName = name; // errorCode = error; // } // // @Override // public String toString() { // if(command == null) // return programName + " exited with code " + errorCode; // else // return "command: " + Arrays.toString(command) + "\n" + programName + " exited with code " + errorCode; // } // // // // } // Path: halvade/src/be/ugent/intec/halvade/utils/ProcessBuilderWrapper.java import be.ugent.intec.halvade.tools.ProcessException; import java.io.*; import java.util.Arrays; public void startProcess(PrintStream stdout_, PrintStream stderr_) throws InterruptedException { try { Logger.DEBUG("running command " + Arrays.toString(command)); ProcessBuilder builder = new ProcessBuilder(command); if(libdir != null) { builder.environment().put( "LD_LIBRARY_PATH", "$LD_LIBRARY_PATH:" + libdir); builder.environment().put( "PYTHONPATH", "$PYTHONPATH:" + libdir); } builder.environment().put("CILK_NWORKERS", "" + threads); p = builder.start(); mon = new ProcMon(p); Thread t = new Thread(mon); t.start(); startTime = System.currentTimeMillis(); if(stdout_ != null) { this.stdout = new StreamGobbler(p.getInputStream(), stdout_); this.stdout.start(); } if(stderr_ != null) { this.stderr = new StreamGobbler(p.getErrorStream(), stderr_, "[PROCESS_ERR]"); this.stderr.start(); } stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); } catch (IOException ex) { Logger.EXCEPTION(ex);
throw new ProcessException(ex.getMessage(), -1);
ddcap/halvade
halvade/src/be/ugent/intec/halvade/hadoop/partitioners/ChrRgGroupingComparator.java
// Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/ChromosomeRegion.java // public class ChromosomeRegion implements WritableComparable<ChromosomeRegion> { // protected int chromosome; // protected int position; // protected int reduceNumber; // identifies region in chromosome but every number is unique, so chr is also separate! // // public int getChromosome() { // return chromosome; // } // // public int getPosition() { // return position; // } // // public int getReduceNumber() { // return reduceNumber; // } // // public void setChromosomeRegion(int chromosome, int position, int reducenumber) { // this.chromosome = chromosome; // this.position = position; // this.reduceNumber = reducenumber; // } // // public ChromosomeRegion() { // this.reduceNumber = -1; // this.chromosome = -1; // this.position = -1; // } // // @Override // public void write(DataOutput d) throws IOException { // d.writeInt(chromosome); // d.writeInt(position); // d.writeInt(reduceNumber); // } // // @Override // public void readFields(DataInput di) throws IOException { // chromosome = di.readInt(); // position = di.readInt(); // reduceNumber = di.readInt(); // } // // @Override // public int compareTo(ChromosomeRegion t) { // /* // * returns: // * x < 0 if t is less than this // * 0 if equals // * x > 0 if t is bigger than this // */ // // if(chromosome == t.chromosome) { // if(reduceNumber == t.reduceNumber) // return position - t.position; // else // return reduceNumber - t.reduceNumber; // // } else // // return chromosome - t.chromosome; // } // // @Override // public String toString() { // return "region_" + reduceNumber; // } // public String toFullString() { // return chromosome + "-" + reduceNumber + "-" + position; // } // }
import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator;
/* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.hadoop.partitioners; /** * * @author ddecap */ public class ChrRgGroupingComparator extends WritableComparator { protected ChrRgGroupingComparator() {
// Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/ChromosomeRegion.java // public class ChromosomeRegion implements WritableComparable<ChromosomeRegion> { // protected int chromosome; // protected int position; // protected int reduceNumber; // identifies region in chromosome but every number is unique, so chr is also separate! // // public int getChromosome() { // return chromosome; // } // // public int getPosition() { // return position; // } // // public int getReduceNumber() { // return reduceNumber; // } // // public void setChromosomeRegion(int chromosome, int position, int reducenumber) { // this.chromosome = chromosome; // this.position = position; // this.reduceNumber = reducenumber; // } // // public ChromosomeRegion() { // this.reduceNumber = -1; // this.chromosome = -1; // this.position = -1; // } // // @Override // public void write(DataOutput d) throws IOException { // d.writeInt(chromosome); // d.writeInt(position); // d.writeInt(reduceNumber); // } // // @Override // public void readFields(DataInput di) throws IOException { // chromosome = di.readInt(); // position = di.readInt(); // reduceNumber = di.readInt(); // } // // @Override // public int compareTo(ChromosomeRegion t) { // /* // * returns: // * x < 0 if t is less than this // * 0 if equals // * x > 0 if t is bigger than this // */ // // if(chromosome == t.chromosome) { // if(reduceNumber == t.reduceNumber) // return position - t.position; // else // return reduceNumber - t.reduceNumber; // // } else // // return chromosome - t.chromosome; // } // // @Override // public String toString() { // return "region_" + reduceNumber; // } // public String toFullString() { // return chromosome + "-" + reduceNumber + "-" + position; // } // } // Path: halvade/src/be/ugent/intec/halvade/hadoop/partitioners/ChrRgGroupingComparator.java import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; /* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade.hadoop.partitioners; /** * * @author ddecap */ public class ChrRgGroupingComparator extends WritableComparator { protected ChrRgGroupingComparator() {
super(ChromosomeRegion.class, true);
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // }
import be.ugent.intec.halvade.uploader.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit;
allReaders = new FileReaderFactory(threads, fromHDFS); } return allReaders; } public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { if (fileB == null) { return new SingleFastQReader(fromHDFS, fileA, interleaved); } else { return new PairedFastQReader(fromHDFS, fileA, fileB); } } public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); } public void addReader(BaseFileReader reader) { readers.add(reader); } public ReadBlock retrieveBlock() { try { ReadBlock block = null; while((check || blocks.size() > 0) && block == null) { block = blocks.poll(1000, TimeUnit.MILLISECONDS); } return block; } catch (InterruptedException ex) {
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java import be.ugent.intec.halvade.uploader.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; allReaders = new FileReaderFactory(threads, fromHDFS); } return allReaders; } public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException { if (fileB == null) { return new SingleFastQReader(fromHDFS, fileA, interleaved); } else { return new PairedFastQReader(fromHDFS, fileA, fileB); } } public void addReader(String fileA, String fileB, boolean interleaved) throws IOException { readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved)); } public void addReader(BaseFileReader reader) { readers.add(reader); } public ReadBlock retrieveBlock() { try { ReadBlock block = null; while((check || blocks.size() > 0) && block == null) { block = blocks.poll(1000, TimeUnit.MILLISECONDS); } return block; } catch (InterruptedException ex) {
Logger.EXCEPTION(ex);
ddcap/halvade
halvade/src/be/ugent/intec/halvade/Halvade.java
// Path: halvade/src/be/ugent/intec/halvade/utils/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void PROFILE(String message) { // System.err.println("[PROFILE] [" + Timer.getGlobalTime() + "] " + message); // } // }
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ToolRunner; import be.ugent.intec.halvade.utils.Logger;
/* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade; /** * * @author ddecap * HALVADE: Hadoop ALigner and VAriant DEtection */ public class Halvade { /** * @param args the command line arguments */ public static void main(String[] args) { // the mapreduce job runMapReduce(args); } public static void runMapReduce(String[] args) { int res = 0; try { Configuration c = new Configuration(); MapReduceRunner runner = new MapReduceRunner(); res = ToolRunner.run(c, runner, args); } catch (Exception ex) {
// Path: halvade/src/be/ugent/intec/halvade/utils/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void PROFILE(String message) { // System.err.println("[PROFILE] [" + Timer.getGlobalTime() + "] " + message); // } // } // Path: halvade/src/be/ugent/intec/halvade/Halvade.java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ToolRunner; import be.ugent.intec.halvade.utils.Logger; /* * Copyright (C) 2014 ddecap * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package be.ugent.intec.halvade; /** * * @author ddecap * HALVADE: Hadoop ALigner and VAriant DEtection */ public class Halvade { /** * @param args the command line arguments */ public static void main(String[] args) { // the mapreduce job runMapReduce(args); } public static void runMapReduce(String[] args) { int res = 0; try { Configuration c = new Configuration(); MapReduceRunner runner = new MapReduceRunner(); res = ToolRunner.run(c, runner, args); } catch (Exception ex) {
Logger.EXCEPTION(ex);
ddcap/halvade
halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/PairedFastQReader.java
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // }
import be.ugent.intec.halvade.uploader.Logger; import java.io.BufferedReader; import java.io.IOException;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class PairedFastQReader extends BaseFileReader { protected BufferedReader readerA, readerB; protected ReadBlock block; public PairedFastQReader(boolean fromHDFS, String fileA, String fileB) throws IOException { super(true); readerA = getReader(fromHDFS, fileA); readerB = getReader(fromHDFS, fileB); toStr = fileA + " & " + fileB;
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java // public class Logger { // /* // * levels of debugging // * 0: INFO // * 1: DEBUG // * 2: EXCEPTION // * 3:ALL // */ // private static int LEVEL = 2; // private static final int EXCEPTION = 2; // private static final int DEBUG = 1; // private static final int INFO = 0; // // // // TODO use configuration set LEVEL // public static void SETLEVEL(int NEWLEVEL) { // LEVEL = NEWLEVEL; // } // // public static void EXCEPTION(Exception ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void THROWABLE(Throwable ex){ // if (LEVEL >= EXCEPTION) { // System.err.println("[EXCEPTION] " + ex.getLocalizedMessage()); // ex.printStackTrace(); // } // } // // public static void DEBUG(String message) { // if(LEVEL >= DEBUG) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // // public static void INFO(String message) { // if(LEVEL >= INFO) // System.err.println("[INFO] " + message); // } // // public static void DEBUG(String message, int level) { // if(LEVEL >= level) // System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message); // } // } // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/PairedFastQReader.java import be.ugent.intec.halvade.uploader.Logger; import java.io.BufferedReader; import java.io.IOException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.ugent.intec.halvade.uploader.input; /** * * @author ddecap */ public class PairedFastQReader extends BaseFileReader { protected BufferedReader readerA, readerB; protected ReadBlock block; public PairedFastQReader(boolean fromHDFS, String fileA, String fileB) throws IOException { super(true); readerA = getReader(fromHDFS, fileA); readerB = getReader(fromHDFS, fileB); toStr = fileA + " & " + fileB;
Logger.DEBUG("Paired: " + toStr);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/Arrays.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class Arrays { public static void compliant(User user) { String name = user.getName(); String[] arr = new String[2]; arr[0] = name; String notTheName = arr[1];
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/Arrays.java import static util.Logger.log; import util.User; package tests; public class Arrays { public static void compliant(User user) { String name = user.getName(); String[] arr = new String[2]; arr[0] = name; String notTheName = arr[1];
log(notTheName);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/InstanceField.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class InstanceField { public static void noncompliant(boolean b, User user) { String a; if(b) a = user.getName(); else a = user.getName(); DataStructure ds1 = new DataStructure(); ds1.f = a; DataStructure ds2 = new DataStructure(); ds2.f = ds1; DataStructure ds3 = (DataStructure) ds2.f;
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/InstanceField.java import static util.Logger.log; import util.User; package tests; public class InstanceField { public static void noncompliant(boolean b, User user) { String a; if(b) a = user.getName(); else a = user.getName(); DataStructure ds1 = new DataStructure(); ds1.f = a; DataStructure ds2 = new DataStructure(); ds2.f = ds1; DataStructure ds3 = (DataStructure) ds2.f;
log((String)ds3.f);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/CorrelatedCalls.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class CorrelatedCalls { interface A { String foo(String x); String bar(String x); } class B implements A { @Override public String foo(String x) { return x; } @Override public String bar(String x) { return null; } } class C implements A { @Override public String foo(String x) { return null; } @Override public String bar(String x) { return x; } }
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/CorrelatedCalls.java import static util.Logger.log; import util.User; package tests; public class CorrelatedCalls { interface A { String foo(String x); String bar(String x); } class B implements A { @Override public String foo(String x) { return x; } @Override public String bar(String x) { return null; } } class C implements A { @Override public String foo(String x) { return null; } @Override public String bar(String x) { return x; } }
public static void compliant(A a, User user) {
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/CorrelatedCalls.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class CorrelatedCalls { interface A { String foo(String x); String bar(String x); } class B implements A { @Override public String foo(String x) { return x; } @Override public String bar(String x) { return null; } } class C implements A { @Override public String foo(String x) { return null; } @Override public String bar(String x) { return x; } } public static void compliant(A a, User user) { String x = user.getName(); x = a.foo(x); x = a.bar(x);
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/CorrelatedCalls.java import static util.Logger.log; import util.User; package tests; public class CorrelatedCalls { interface A { String foo(String x); String bar(String x); } class B implements A { @Override public String foo(String x) { return x; } @Override public String bar(String x) { return null; } } class C implements A { @Override public String foo(String x) { return null; } @Override public String bar(String x) { return x; } } public static void compliant(A a, User user) { String x = user.getName(); x = a.foo(x); x = a.bar(x);
log(x);
stg-tud/apsa
2016/ifds/testcases/src/test/java/tests/Sanitization.java
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public class SourceAndSink { // // public static Object source() { // return new Object(); // } // // public static void sink(Object obj) { // System.out.println(obj); // } // // public static void sanitize(Object obj) { // // } // }
import static util.SourceAndSink.sink; import static util.SourceAndSink.*;
package tests; public class Sanitization { public static void foo() { Object a = source(); sanitize(a);
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public class SourceAndSink { // // public static Object source() { // return new Object(); // } // // public static void sink(Object obj) { // System.out.println(obj); // } // // public static void sanitize(Object obj) { // // } // } // Path: 2016/ifds/testcases/src/test/java/tests/Sanitization.java import static util.SourceAndSink.sink; import static util.SourceAndSink.*; package tests; public class Sanitization { public static void foo() { Object a = source(); sanitize(a);
sink(a);
stg-tud/apsa
2016/ifds/testcases/src/test/java/tests/CorrelatedCalls.java
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static Object source() { // return new Object(); // }
import static util.SourceAndSink.sink; import static util.SourceAndSink.source;
package tests; public class CorrelatedCalls { interface A { Object foo(Object x); Object bar(Object x); } class B implements A { @Override public Object foo(Object x) { return x; } @Override public Object bar(Object x) { return null; } } class C implements A { @Override public Object foo(Object x) { return null; } @Override public Object bar(Object x) { return x; } } public static void main(A a) {
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static Object source() { // return new Object(); // } // Path: 2016/ifds/testcases/src/test/java/tests/CorrelatedCalls.java import static util.SourceAndSink.sink; import static util.SourceAndSink.source; package tests; public class CorrelatedCalls { interface A { Object foo(Object x); Object bar(Object x); } class B implements A { @Override public Object foo(Object x) { return x; } @Override public Object bar(Object x) { return null; } } class C implements A { @Override public Object foo(Object x) { return null; } @Override public Object bar(Object x) { return x; } } public static void main(A a) {
Object x = source();
stg-tud/apsa
2016/ifds/testcases/src/test/java/tests/CorrelatedCalls.java
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static Object source() { // return new Object(); // }
import static util.SourceAndSink.sink; import static util.SourceAndSink.source;
package tests; public class CorrelatedCalls { interface A { Object foo(Object x); Object bar(Object x); } class B implements A { @Override public Object foo(Object x) { return x; } @Override public Object bar(Object x) { return null; } } class C implements A { @Override public Object foo(Object x) { return null; } @Override public Object bar(Object x) { return x; } } public static void main(A a) { Object x = source(); x = a.foo(x); x = a.bar(x);
// Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static void sink(Object obj) { // System.out.println(obj); // } // // Path: 2016/ifds/testcases/src/test/java/util/SourceAndSink.java // public static Object source() { // return new Object(); // } // Path: 2016/ifds/testcases/src/test/java/tests/CorrelatedCalls.java import static util.SourceAndSink.sink; import static util.SourceAndSink.source; package tests; public class CorrelatedCalls { interface A { Object foo(Object x); Object bar(Object x); } class B implements A { @Override public Object foo(Object x) { return x; } @Override public Object bar(Object x) { return null; } } class C implements A { @Override public Object foo(Object x) { return null; } @Override public Object bar(Object x) { return x; } } public static void main(A a) { Object x = source(); x = a.foo(x); x = a.bar(x);
sink(x);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/InterproceduralStaticEdges.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class InterproceduralStaticEdges { public static void noncompliant(User user) { String name = user.getName(); String d = foo(name);
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/InterproceduralStaticEdges.java import static util.Logger.log; import util.User; package tests; public class InterproceduralStaticEdges { public static void noncompliant(User user) { String name = user.getName(); String d = foo(name);
log(d);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/Assignments.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class Assignments { public static void noncompliant(User user) { String name = user.getName(); String theNameAgain = name;
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/Assignments.java import static util.Logger.log; import util.User; package tests; public class Assignments { public static void noncompliant(User user) { String name = user.getName(); String theNameAgain = name;
log(theNameAgain);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/MultipleInstanceFields.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class MultipleInstanceFields { public static void noncompliant(User user) { String name = user.getName(); DataStructure ds1 = new DataStructure(); ds1.str = name; DataStructure ds2 = new DataStructure(); ds2.rec = ds1; DataStructure ds3 = ds2.rec;
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/MultipleInstanceFields.java import static util.Logger.log; import util.User; package tests; public class MultipleInstanceFields { public static void noncompliant(User user) { String name = user.getName(); DataStructure ds1 = new DataStructure(); ds1.str = name; DataStructure ds2 = new DataStructure(); ds2.rec = ds1; DataStructure ds3 = ds2.rec;
log(ds3.str);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/StaticField.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class StaticField { private static String f;
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/StaticField.java import static util.Logger.log; import util.User; package tests; public class StaticField { private static String f;
public static void foo(User user) {
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/StaticField.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class StaticField { private static String f; public static void foo(User user) { String name = user.getName(); f = name; noncompliant(); } private static void noncompliant() {
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/StaticField.java import static util.Logger.log; import util.User; package tests; public class StaticField { private static String f; public static void foo(User user) { String name = user.getName(); f = name; noncompliant(); } private static void noncompliant() {
log(f);
stg-tud/apsa
2019/10-IFDS/Exercise/test/tests/InterproceduralInstanceBasedEdges.java
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // }
import static util.Logger.log; import util.User;
package tests; public class InterproceduralInstanceBasedEdges { public void noncompliant(User user) { String name = user.getName(); String d = foo(name);
// Path: 2019/10-IFDS/Exercise/test/util/Logger.java // public static void log(String message) { // // } // // Path: 2019/10-IFDS/Exercise/test/util/User.java // public class User { // // public String getName() { // return null; // } // } // Path: 2019/10-IFDS/Exercise/test/tests/InterproceduralInstanceBasedEdges.java import static util.Logger.log; import util.User; package tests; public class InterproceduralInstanceBasedEdges { public void noncompliant(User user) { String name = user.getName(); String d = foo(name);
log(d);
mtsar/mtsar
src/test/java/mtsar/processors/answer/EmptyAggregatorTest.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import org.junit.Test; import java.util.Optional; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregatorTest { private static final Task task = fixture("task1.json", Task.class);
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // Path: src/test/java/mtsar/processors/answer/EmptyAggregatorTest.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import org.junit.Test; import java.util.Optional; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregatorTest { private static final Task task = fixture("task1.json", Task.class);
private static final AnswerAggregator aggregator = new EmptyAggregator();
mtsar/mtsar
src/test/java/mtsar/processors/answer/EmptyAggregatorTest.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import org.junit.Test; import java.util.Optional; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregatorTest { private static final Task task = fixture("task1.json", Task.class); private static final AnswerAggregator aggregator = new EmptyAggregator(); @Test public void testEmptyCase() {
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // Path: src/test/java/mtsar/processors/answer/EmptyAggregatorTest.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import org.junit.Test; import java.util.Optional; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregatorTest { private static final Task task = fixture("task1.json", Task.class); private static final AnswerAggregator aggregator = new EmptyAggregator(); @Test public void testEmptyCase() {
final Optional<AnswerAggregation> winner = aggregator.aggregate(task);
mtsar/mtsar
src/main/java/mtsar/api/sql/AnswerDAO.java
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import java.util.stream.Collectors; import mtsar.api.Answer; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(AnswerDAO.Mapper.class) public interface AnswerDAO { String ANSWER_TYPE_ANSWER = "answer"; String ANSWER_TYPE_DEFAULT = ANSWER_TYPE_ANSWER; String ANSWER_TYPE_SKIP = "skip"; @SqlQuery("select * from answers where stage = :stage")
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/sql/AnswerDAO.java import java.util.stream.Collectors; import mtsar.api.Answer; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(AnswerDAO.Mapper.class) public interface AnswerDAO { String ANSWER_TYPE_ANSWER = "answer"; String ANSWER_TYPE_DEFAULT = ANSWER_TYPE_ANSWER; String ANSWER_TYPE_SKIP = "skip"; @SqlQuery("select * from answers where stage = :stage")
List<Answer> listForStage(@Bind("stage") String stage);
mtsar/mtsar
src/main/java/mtsar/api/AgreementReport.java
// Path: src/main/java/mtsar/api/sql/AnswerDAO.java // @UseStringTemplate3StatementLocator // @RegisterMapper(AnswerDAO.Mapper.class) // public interface AnswerDAO { // String ANSWER_TYPE_ANSWER = "answer"; // String ANSWER_TYPE_DEFAULT = ANSWER_TYPE_ANSWER; // String ANSWER_TYPE_SKIP = "skip"; // // @SqlQuery("select * from answers where stage = :stage") // List<Answer> listForStage(@Bind("stage") String stage); // // @SqlQuery("select * from answers where task_id = :taskId and stage = :stage") // List<Answer> listForTask(@Bind("taskId") Integer taskId, @Bind("stage") String stage); // // @SqlQuery("select * from answers where worker_id = :workerId and stage = :stage") // List<Answer> listForWorker(@Bind("workerId") Integer workerId, @Bind("stage") String stage); // // @SqlQuery("select * from answers where id = :id and stage = :stage limit 1") // Answer find(@Bind("id") Integer id, @Bind("stage") String stage); // // @SqlQuery("select * from answers where stage = :stage and worker_id = :worker_id and task_id = :task_id limit 1") // Answer findByWorkerAndTask(@Bind("stage") String stage, @Bind("worker_id") Integer workerId, @Bind("task_id") Integer taskId); // // @SqlQuery("insert into answers (stage, datetime, tags, type, worker_id, task_id, answers) values (:stage, coalesce(:dateTime, localtimestamp), cast(:tagsTextArray as text[]), cast(:type as answer_type), :workerId, :taskId, cast(:answersTextArray as text[])) returning id") // int insert(@BindBean Answer a); // // @SqlBatch("insert into answers (id, stage, datetime, tags, type, worker_id, task_id, answers) values (coalesce(:id, nextval('answers_id_seq')), :stage, coalesce(:dateTime, localtimestamp), cast(:tagsTextArray as text[]), cast(:type as answer_type), :workerId, :taskId, cast(:answersTextArray as text[]))") // @BatchChunkSize(1000) // int[] insert(@BindBean Iterator<Answer> answers); // // /* // * This is a slow method for inserting the given collection of answers and returning all the inserted objects. // */ // static List<Answer> insert(AnswerDAO dao, Collection<Answer> answers) { // return answers.stream().map(answer -> dao.find(dao.insert(answer), answer.getStage())).collect(Collectors.toList()); // } // // @SqlQuery("select count(*) from answers") // int count(); // // @SqlQuery("select count(*) from answers where stage = :stage") // int count(@Bind("stage") String stage); // // @SqlUpdate("delete from answers where id = :id and stage = :stage") // void delete(@Bind("id") Integer id, @Bind("stage") String stage); // // @SqlUpdate("delete from answers where stage = :stage") // void deleteAll(@Bind("stage") String stage); // // @SqlUpdate("delete from answers") // void deleteAll(); // // @SqlUpdate("select setval('answers_id_seq', coalesce((select max(id) + 1 from answers), 1), false)") // void resetSequence(); // // void close(); // // class Mapper implements ResultSetMapper<Answer> { // @Override // public Answer map(int index, ResultSet r, StatementContext ctx) throws SQLException { // return new Answer.Builder(). // setId(r.getInt("id")). // setStage(r.getString("stage")). // setDateTime(r.getTimestamp("datetime")). // addAllTags(Arrays.asList((String[]) r.getArray("tags").getArray())). // setMetadata(r.getString("metadata")). // setType(r.getString("type")). // setWorkerId(r.getInt("worker_id")). // setTaskId(r.getInt("task_id")). // addAllAnswers(Arrays.asList((String[]) r.getArray("answers").getArray())). // build(); // } // } // }
import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import de.tudarmstadt.ukp.dkpro.statistics.agreement.coding.*; import de.tudarmstadt.ukp.dkpro.statistics.agreement.distance.NominalDistanceFunction; import de.tudarmstadt.ukp.dkpro.statistics.agreement.distance.OrdinalDistanceFunction; import mtsar.api.sql.AnswerDAO; import org.inferred.freebuilder.FreeBuilder; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; /** * Experimental wrapper for various agreement tests. */ @FreeBuilder @XmlRootElement @JsonDeserialize(builder = AgreementReport.Builder.class) public interface AgreementReport { @JsonProperty double getPercentage(); @JsonProperty double getWeightedKappa(); @JsonProperty double getNominalAlpha(); @JsonProperty double getOrdinalAlpha(); @JsonProperty double getRandolphKappa(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends AgreementReport_Builder {
// Path: src/main/java/mtsar/api/sql/AnswerDAO.java // @UseStringTemplate3StatementLocator // @RegisterMapper(AnswerDAO.Mapper.class) // public interface AnswerDAO { // String ANSWER_TYPE_ANSWER = "answer"; // String ANSWER_TYPE_DEFAULT = ANSWER_TYPE_ANSWER; // String ANSWER_TYPE_SKIP = "skip"; // // @SqlQuery("select * from answers where stage = :stage") // List<Answer> listForStage(@Bind("stage") String stage); // // @SqlQuery("select * from answers where task_id = :taskId and stage = :stage") // List<Answer> listForTask(@Bind("taskId") Integer taskId, @Bind("stage") String stage); // // @SqlQuery("select * from answers where worker_id = :workerId and stage = :stage") // List<Answer> listForWorker(@Bind("workerId") Integer workerId, @Bind("stage") String stage); // // @SqlQuery("select * from answers where id = :id and stage = :stage limit 1") // Answer find(@Bind("id") Integer id, @Bind("stage") String stage); // // @SqlQuery("select * from answers where stage = :stage and worker_id = :worker_id and task_id = :task_id limit 1") // Answer findByWorkerAndTask(@Bind("stage") String stage, @Bind("worker_id") Integer workerId, @Bind("task_id") Integer taskId); // // @SqlQuery("insert into answers (stage, datetime, tags, type, worker_id, task_id, answers) values (:stage, coalesce(:dateTime, localtimestamp), cast(:tagsTextArray as text[]), cast(:type as answer_type), :workerId, :taskId, cast(:answersTextArray as text[])) returning id") // int insert(@BindBean Answer a); // // @SqlBatch("insert into answers (id, stage, datetime, tags, type, worker_id, task_id, answers) values (coalesce(:id, nextval('answers_id_seq')), :stage, coalesce(:dateTime, localtimestamp), cast(:tagsTextArray as text[]), cast(:type as answer_type), :workerId, :taskId, cast(:answersTextArray as text[]))") // @BatchChunkSize(1000) // int[] insert(@BindBean Iterator<Answer> answers); // // /* // * This is a slow method for inserting the given collection of answers and returning all the inserted objects. // */ // static List<Answer> insert(AnswerDAO dao, Collection<Answer> answers) { // return answers.stream().map(answer -> dao.find(dao.insert(answer), answer.getStage())).collect(Collectors.toList()); // } // // @SqlQuery("select count(*) from answers") // int count(); // // @SqlQuery("select count(*) from answers where stage = :stage") // int count(@Bind("stage") String stage); // // @SqlUpdate("delete from answers where id = :id and stage = :stage") // void delete(@Bind("id") Integer id, @Bind("stage") String stage); // // @SqlUpdate("delete from answers where stage = :stage") // void deleteAll(@Bind("stage") String stage); // // @SqlUpdate("delete from answers") // void deleteAll(); // // @SqlUpdate("select setval('answers_id_seq', coalesce((select max(id) + 1 from answers), 1), false)") // void resetSequence(); // // void close(); // // class Mapper implements ResultSetMapper<Answer> { // @Override // public Answer map(int index, ResultSet r, StatementContext ctx) throws SQLException { // return new Answer.Builder(). // setId(r.getInt("id")). // setStage(r.getString("stage")). // setDateTime(r.getTimestamp("datetime")). // addAllTags(Arrays.asList((String[]) r.getArray("tags").getArray())). // setMetadata(r.getString("metadata")). // setType(r.getString("type")). // setWorkerId(r.getInt("worker_id")). // setTaskId(r.getInt("task_id")). // addAllAnswers(Arrays.asList((String[]) r.getArray("answers").getArray())). // build(); // } // } // } // Path: src/main/java/mtsar/api/AgreementReport.java import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import de.tudarmstadt.ukp.dkpro.statistics.agreement.coding.*; import de.tudarmstadt.ukp.dkpro.statistics.agreement.distance.NominalDistanceFunction; import de.tudarmstadt.ukp.dkpro.statistics.agreement.distance.OrdinalDistanceFunction; import mtsar.api.sql.AnswerDAO; import org.inferred.freebuilder.FreeBuilder; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; /** * Experimental wrapper for various agreement tests. */ @FreeBuilder @XmlRootElement @JsonDeserialize(builder = AgreementReport.Builder.class) public interface AgreementReport { @JsonProperty double getPercentage(); @JsonProperty double getWeightedKappa(); @JsonProperty double getNominalAlpha(); @JsonProperty double getOrdinalAlpha(); @JsonProperty double getRandolphKappa(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends AgreementReport_Builder {
public Builder compute(Stage stage, AnswerDAO answerDAO) {
mtsar/mtsar
src/test/java/mtsar/PostgresUtilsTest.java
// Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import mtsar.util.PostgresUtils; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class PostgresUtilsTest { @Test public void testEmpty() {
// Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/test/java/mtsar/PostgresUtilsTest.java import mtsar.util.PostgresUtils; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class PostgresUtilsTest { @Test public void testEmpty() {
assertThat(PostgresUtils.buildArrayString(new String[]{})).isEqualTo("{}");
mtsar/mtsar
src/main/java/mtsar/api/Task.java
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map;
@JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonProperty String getType(); @JsonProperty String getDescription(); @JsonProperty List<String> getAnswers(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonIgnore String getAnswersTextArray(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Task_Builder { public Builder() {
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Task.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map; @JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonProperty String getType(); @JsonProperty String getDescription(); @JsonProperty List<String> getAnswers(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonIgnore String getAnswersTextArray(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Task_Builder { public Builder() {
setDateTime(DateTimeUtils.now());
mtsar/mtsar
src/main/java/mtsar/api/Task.java
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map;
List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonProperty String getType(); @JsonProperty String getDescription(); @JsonProperty List<String> getAnswers(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonIgnore String getAnswersTextArray(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Task_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setMetadata(String json) {
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Task.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map; List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonProperty String getType(); @JsonProperty String getDescription(); @JsonProperty List<String> getAnswers(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonIgnore String getAnswersTextArray(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Task_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setMetadata(String json) {
return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json));
mtsar/mtsar
src/main/java/mtsar/api/Stage.java
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition;
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Stage.java import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition;
private final WorkerRanker workerRanker;
mtsar/mtsar
src/main/java/mtsar/api/Stage.java
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition; private final WorkerRanker workerRanker;
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Stage.java import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition; private final WorkerRanker workerRanker;
private final TaskAllocator taskAllocator;
mtsar/mtsar
src/main/java/mtsar/api/Stage.java
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition; private final WorkerRanker workerRanker; private final TaskAllocator taskAllocator;
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Stage.java import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @XmlRootElement public class Stage { private final Definition definition; private final WorkerRanker workerRanker; private final TaskAllocator taskAllocator;
private final AnswerAggregator answerAggregator;
mtsar/mtsar
src/main/java/mtsar/api/Stage.java
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp;
@XmlRootElement @JsonDeserialize(builder = Definition.Builder.class) public interface Definition { @JsonProperty String getId(); @JsonProperty Timestamp getDateTime(); @JsonProperty String getDescription(); @JsonProperty() String getWorkerRanker(); @JsonProperty() String getTaskAllocator(); @JsonProperty() String getAnswerAggregator(); @JsonProperty Map<String, String> getOptions(); @JsonIgnore String getOptionsJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Stage_Definition_Builder { public Builder() {
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Stage.java import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; @XmlRootElement @JsonDeserialize(builder = Definition.Builder.class) public interface Definition { @JsonProperty String getId(); @JsonProperty Timestamp getDateTime(); @JsonProperty String getDescription(); @JsonProperty() String getWorkerRanker(); @JsonProperty() String getTaskAllocator(); @JsonProperty() String getAnswerAggregator(); @JsonProperty Map<String, String> getOptions(); @JsonIgnore String getOptionsJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Stage_Definition_Builder { public Builder() {
setDateTime(DateTimeUtils.now());
mtsar/mtsar
src/main/java/mtsar/api/Stage.java
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp;
String getId(); @JsonProperty Timestamp getDateTime(); @JsonProperty String getDescription(); @JsonProperty() String getWorkerRanker(); @JsonProperty() String getTaskAllocator(); @JsonProperty() String getAnswerAggregator(); @JsonProperty Map<String, String> getOptions(); @JsonIgnore String getOptionsJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Stage_Definition_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setOptions(String json) {
// Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // // Path: src/main/java/mtsar/processors/TaskAllocator.java // public interface TaskAllocator { // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * // * @param worker worker. // * @param n maximum number of tasks to be allocated. // * @return Allocated tasks. // */ // @Nonnull // Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n); // // /** // * Given a worker, an allocator returns either an allocated task, or nothing. // * This is an alias for the method accepting the number of allocated tasks. // * // * @param worker worker. // * @return Allocated task. // */ // @Nonnull // default Optional<TaskAllocation> allocate(@Nonnull Worker worker) { // return allocate(worker, 1); // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // // Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Stage.java import java.util.Map; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.processors.AnswerAggregator; import mtsar.processors.TaskAllocator; import mtsar.processors.WorkerRanker; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.inject.Inject; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; String getId(); @JsonProperty Timestamp getDateTime(); @JsonProperty String getDescription(); @JsonProperty() String getWorkerRanker(); @JsonProperty() String getTaskAllocator(); @JsonProperty() String getAnswerAggregator(); @JsonProperty Map<String, String> getOptions(); @JsonIgnore String getOptionsJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Stage_Definition_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setOptions(String json) {
return putAllOptions(PostgresUtils.parseJSONString(json));
mtsar/mtsar
src/main/java/mtsar/processors/TaskAllocator.java
// Path: src/main/java/mtsar/api/TaskAllocation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = TaskAllocation.Builder.class) // public interface TaskAllocation { // String TYPE_DEFAULT = "allocation"; // // @JsonProperty // String getType(); // // @JsonProperty // Worker getWorker(); // // @JsonProperty // List<Task> getTasks(); // // @JsonProperty // int getTaskRemaining(); // // @JsonProperty // int getTaskCount(); // // @JsonIgnore // default Optional<Task> getTask() { // if (getTasks().isEmpty()) return Optional.empty(); // return Optional.of(getTasks().get(0)); // } // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends TaskAllocation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import mtsar.api.TaskAllocation; import mtsar.api.Worker; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.Optional;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; /** * Task allocator is a processor that allocates tasks to the crowd workers. */ public interface TaskAllocator { /** * Given a worker, an allocator returns either an allocated task, or nothing. * * @param worker worker. * @param n maximum number of tasks to be allocated. * @return Allocated tasks. */ @Nonnull
// Path: src/main/java/mtsar/api/TaskAllocation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = TaskAllocation.Builder.class) // public interface TaskAllocation { // String TYPE_DEFAULT = "allocation"; // // @JsonProperty // String getType(); // // @JsonProperty // Worker getWorker(); // // @JsonProperty // List<Task> getTasks(); // // @JsonProperty // int getTaskRemaining(); // // @JsonProperty // int getTaskCount(); // // @JsonIgnore // default Optional<Task> getTask() { // if (getTasks().isEmpty()) return Optional.empty(); // return Optional.of(getTasks().get(0)); // } // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends TaskAllocation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/processors/TaskAllocator.java import mtsar.api.TaskAllocation; import mtsar.api.Worker; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.Optional; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; /** * Task allocator is a processor that allocates tasks to the crowd workers. */ public interface TaskAllocator { /** * Given a worker, an allocator returns either an allocated task, or nothing. * * @param worker worker. * @param n maximum number of tasks to be allocated. * @return Allocated tasks. */ @Nonnull
Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n);
mtsar/mtsar
src/main/java/mtsar/processors/TaskAllocator.java
// Path: src/main/java/mtsar/api/TaskAllocation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = TaskAllocation.Builder.class) // public interface TaskAllocation { // String TYPE_DEFAULT = "allocation"; // // @JsonProperty // String getType(); // // @JsonProperty // Worker getWorker(); // // @JsonProperty // List<Task> getTasks(); // // @JsonProperty // int getTaskRemaining(); // // @JsonProperty // int getTaskCount(); // // @JsonIgnore // default Optional<Task> getTask() { // if (getTasks().isEmpty()) return Optional.empty(); // return Optional.of(getTasks().get(0)); // } // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends TaskAllocation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import mtsar.api.TaskAllocation; import mtsar.api.Worker; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.Optional;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; /** * Task allocator is a processor that allocates tasks to the crowd workers. */ public interface TaskAllocator { /** * Given a worker, an allocator returns either an allocated task, or nothing. * * @param worker worker. * @param n maximum number of tasks to be allocated. * @return Allocated tasks. */ @Nonnull
// Path: src/main/java/mtsar/api/TaskAllocation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = TaskAllocation.Builder.class) // public interface TaskAllocation { // String TYPE_DEFAULT = "allocation"; // // @JsonProperty // String getType(); // // @JsonProperty // Worker getWorker(); // // @JsonProperty // List<Task> getTasks(); // // @JsonProperty // int getTaskRemaining(); // // @JsonProperty // int getTaskCount(); // // @JsonIgnore // default Optional<Task> getTask() { // if (getTasks().isEmpty()) return Optional.empty(); // return Optional.of(getTasks().get(0)); // } // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends TaskAllocation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/processors/TaskAllocator.java import mtsar.api.TaskAllocation; import mtsar.api.Worker; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.Optional; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; /** * Task allocator is a processor that allocates tasks to the crowd workers. */ public interface TaskAllocator { /** * Given a worker, an allocator returns either an allocated task, or nothing. * * @param worker worker. * @param n maximum number of tasks to be allocated. * @return Allocated tasks. */ @Nonnull
Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n);
mtsar/mtsar
src/main/java/mtsar/processors/worker/RandomRanker.java
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // }
import mtsar.api.Worker; import mtsar.api.WorkerRanking; import mtsar.processors.WorkerRanker; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.worker; public class RandomRanker implements WorkerRanker { @Override @Nonnull
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // Path: src/main/java/mtsar/processors/worker/RandomRanker.java import mtsar.api.Worker; import mtsar.api.WorkerRanking; import mtsar.processors.WorkerRanker; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.worker; public class RandomRanker implements WorkerRanker { @Override @Nonnull
public Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers) {
mtsar/mtsar
src/test/java/mtsar/ParamsUtilsTest.java
// Path: src/main/java/mtsar/util/ParamsUtils.java // @ParametersAreNonnullByDefault // public final class ParamsUtils { // @Nullable // public static <T> T optional(Optional<T> optional) { // return optional.isPresent() ? optional.get() : null; // } // // @Nonnull // public static Map<String, List<String>> nested(MultivaluedMap<String, String> params, String prefix) { // requireNonNull(params); // requireNonNull(prefix); // final Pattern pattern = Pattern.compile("^(" + Pattern.quote(prefix) + "\\[(\\w+?)\\])(\\[\\d+\\]|)$"); // // final Map<String, Matcher> prefixes = params.keySet().stream(). // map(pattern::matcher). // filter(Matcher::matches). // collect(Collectors.toMap(matcher -> matcher.group(1), Function.identity(), (m1, m2) -> m1)); // // final Map<String, List<String>> values = prefixes.entrySet().stream(). // collect(Collectors.toMap(entry -> entry.getValue().group(2), entry -> extract(params, entry.getKey()))); // // return values; // } // // @Nonnull // public static List<String> extract(MultivaluedMap<String, String> params, String prefix) { // requireNonNull(params); // requireNonNull(prefix); // final String regexp = "^" + Pattern.quote(prefix) + "(\\[\\d+\\]|)$"; // // final List<String> values = params.entrySet().stream(). // filter(entries -> entries.getKey().matches(regexp) && entries.getValue() != null && !entries.getValue().isEmpty()). // flatMap(entries -> entries.getValue().stream().filter(value -> value != null && !value.isEmpty())). // collect(Collectors.toList()); // // return values; // } // // public static Set<ConstraintViolation<Object>> validate(Validator validator, Object... objects) { // requireNonNull(validator); // final Set<ConstraintViolation<Object>> violations = new HashSet<>(); // for (final Object object : objects) violations.addAll(validator.validate(object)); // return violations; // } // }
import mtsar.util.ParamsUtils; import org.junit.Test; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ParamsUtilsTest { @Test public void testExtractSingle() { final MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("foo", "bar");
// Path: src/main/java/mtsar/util/ParamsUtils.java // @ParametersAreNonnullByDefault // public final class ParamsUtils { // @Nullable // public static <T> T optional(Optional<T> optional) { // return optional.isPresent() ? optional.get() : null; // } // // @Nonnull // public static Map<String, List<String>> nested(MultivaluedMap<String, String> params, String prefix) { // requireNonNull(params); // requireNonNull(prefix); // final Pattern pattern = Pattern.compile("^(" + Pattern.quote(prefix) + "\\[(\\w+?)\\])(\\[\\d+\\]|)$"); // // final Map<String, Matcher> prefixes = params.keySet().stream(). // map(pattern::matcher). // filter(Matcher::matches). // collect(Collectors.toMap(matcher -> matcher.group(1), Function.identity(), (m1, m2) -> m1)); // // final Map<String, List<String>> values = prefixes.entrySet().stream(). // collect(Collectors.toMap(entry -> entry.getValue().group(2), entry -> extract(params, entry.getKey()))); // // return values; // } // // @Nonnull // public static List<String> extract(MultivaluedMap<String, String> params, String prefix) { // requireNonNull(params); // requireNonNull(prefix); // final String regexp = "^" + Pattern.quote(prefix) + "(\\[\\d+\\]|)$"; // // final List<String> values = params.entrySet().stream(). // filter(entries -> entries.getKey().matches(regexp) && entries.getValue() != null && !entries.getValue().isEmpty()). // flatMap(entries -> entries.getValue().stream().filter(value -> value != null && !value.isEmpty())). // collect(Collectors.toList()); // // return values; // } // // public static Set<ConstraintViolation<Object>> validate(Validator validator, Object... objects) { // requireNonNull(validator); // final Set<ConstraintViolation<Object>> violations = new HashSet<>(); // for (final Object object : objects) violations.addAll(validator.validate(object)); // return violations; // } // } // Path: src/test/java/mtsar/ParamsUtilsTest.java import mtsar.util.ParamsUtils; import org.junit.Test; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ParamsUtilsTest { @Test public void testExtractSingle() { final MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("foo", "bar");
final List<String> values = ParamsUtils.extract(params, "foo");
mtsar/mtsar
src/main/java/mtsar/processors/answer/EmptyAggregator.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregator implements AnswerAggregator { @Override @Nonnull
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // Path: src/main/java/mtsar/processors/answer/EmptyAggregator.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregator implements AnswerAggregator { @Override @Nonnull
public Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks) {
mtsar/mtsar
src/main/java/mtsar/processors/answer/EmptyAggregator.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregator implements AnswerAggregator { @Override @Nonnull
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/AnswerAggregator.java // public interface AnswerAggregator { // /** // * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. // * // * @param tasks tasks. // * @return Aggregated answers. // */ // @Nonnull // Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks); // // /** // * Given a task, an aggregator returns either an aggregated answer, or nothing. // * This is an alias for the method accepting the task collection. // * // * @param task task. // * @return Aggregated answer. // */ // @Nonnull // default Optional<AnswerAggregation> aggregate(@Nonnull Task task) { // final Map<Integer, AnswerAggregation> aggregations = aggregate(Collections.singletonList(task)); // if (aggregations.isEmpty()) return Optional.empty(); // return Optional.of(aggregations.get(task.getId())); // } // } // Path: src/main/java/mtsar/processors/answer/EmptyAggregator.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import mtsar.processors.AnswerAggregator; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class EmptyAggregator implements AnswerAggregator { @Override @Nonnull
public Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks) {
mtsar/mtsar
src/main/java/mtsar/processors/worker/ZeroRanker.java
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // }
import mtsar.api.Worker; import mtsar.api.WorkerRanking; import mtsar.processors.WorkerRanker; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.worker; public class ZeroRanker implements WorkerRanker { @Override @Nonnull
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/processors/WorkerRanker.java // public interface WorkerRanker { // /** // * Given a collection of workers, estimate their performance. // * // * @param workers workers. // * @return Worker rankings. // */ // @Nonnull // Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers); // // /** // * Given a worker, a ranker returns either a worker ranking, or nothing. // * This is an alias for the method accepting the worker collection. // * // * @param worker worker. // * @return Worker ranking. // */ // @Nonnull // default Optional<WorkerRanking> rank(@Nonnull Worker worker) { // final Map<Integer, WorkerRanking> rankings = rank(Collections.singletonList(worker)); // if (rankings.isEmpty()) return Optional.empty(); // return Optional.of(rankings.get(worker.getId())); // } // } // Path: src/main/java/mtsar/processors/worker/ZeroRanker.java import mtsar.api.Worker; import mtsar.api.WorkerRanking; import mtsar.processors.WorkerRanker; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.worker; public class ZeroRanker implements WorkerRanker { @Override @Nonnull
public Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers) {
mtsar/mtsar
src/main/java/mtsar/api/sql/StageDAO.java
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // }
import mtsar.api.Stage; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @RegisterMapper(StageDAO.Mapper.class) public interface StageDAO { @SqlQuery("select * from stages where id = :id limit 1")
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // } // Path: src/main/java/mtsar/api/sql/StageDAO.java import mtsar.api.Stage; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @RegisterMapper(StageDAO.Mapper.class) public interface StageDAO { @SqlQuery("select * from stages where id = :id limit 1")
Stage.Definition find(@Bind("id") String id);
mtsar/mtsar
src/main/java/mtsar/api/csv/AnswerAggregationCSV.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // }
import mtsar.api.AnswerAggregation; import org.apache.commons.csv.CSVFormat; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Comparator;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class AnswerAggregationCSV { private static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"task_id", "answers"};
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // Path: src/main/java/mtsar/api/csv/AnswerAggregationCSV.java import mtsar.api.AnswerAggregation; import org.apache.commons.csv.CSVFormat; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Comparator; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class AnswerAggregationCSV { private static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"task_id", "answers"};
private static final Comparator<AnswerAggregation> ORDER = (a1, a2) -> a1.getTask().getId().compareTo(a2.getTask().getId());
mtsar/mtsar
src/test/java/mtsar/processors/answer/AnswerAggregationTest.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import org.junit.Test; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class AnswerAggregationTest { private static final Task task = fixture("task1.json", Task.class); @Test public void testDefault() {
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/test/java/mtsar/TestHelper.java // public static <T> T fixture(String filename, Class<T> valueType) { // try { // return JSON.readValue(FixtureHelpers.fixture("fixtures/" + filename), valueType); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // Path: src/test/java/mtsar/processors/answer/AnswerAggregationTest.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import org.junit.Test; import static mtsar.TestHelper.fixture; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors.answer; public class AnswerAggregationTest { private static final Task task = fixture("task1.json", Task.class); @Test public void testDefault() {
final AnswerAggregation aggregation = new AnswerAggregation.Builder().setTask(task).build();
mtsar/mtsar
src/main/java/mtsar/api/sql/EventDAO.java
// Path: src/main/java/mtsar/api/Event.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Event.Builder.class) // public interface Event { // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Event_Builder { // } // }
import mtsar.api.Event; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @RegisterMapper(EventDAO.Mapper.class) public interface EventDAO { void close();
// Path: src/main/java/mtsar/api/Event.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Event.Builder.class) // public interface Event { // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Event_Builder { // } // } // Path: src/main/java/mtsar/api/sql/EventDAO.java import mtsar.api.Event; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @RegisterMapper(EventDAO.Mapper.class) public interface EventDAO { void close();
class Mapper implements ResultSetMapper<Event> {
mtsar/mtsar
src/main/java/mtsar/processors/AnswerAggregator.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface AnswerAggregator { /** * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. * * @param tasks tasks. * @return Aggregated answers. */ @Nonnull
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/processors/AnswerAggregator.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface AnswerAggregator { /** * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. * * @param tasks tasks. * @return Aggregated answers. */ @Nonnull
Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks);
mtsar/mtsar
src/main/java/mtsar/processors/AnswerAggregator.java
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import mtsar.api.AnswerAggregation; import mtsar.api.Task; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface AnswerAggregator { /** * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. * * @param tasks tasks. * @return Aggregated answers. */ @Nonnull
// Path: src/main/java/mtsar/api/AnswerAggregation.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = AnswerAggregation.Builder.class) // public interface AnswerAggregation { // String TYPE_DEFAULT = "aggregation"; // String TYPE_EMPTY = "empty"; // // static AnswerAggregation empty(Task task) { // return new Builder().setType(TYPE_EMPTY).setTask(task).build(); // } // // @JsonProperty // String getType(); // // @JsonProperty // Task getTask(); // // @JsonProperty // List<String> getAnswers(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends AnswerAggregation_Builder { // public Builder() { // setType(TYPE_DEFAULT); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/processors/AnswerAggregator.java import mtsar.api.AnswerAggregation; import mtsar.api.Task; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface AnswerAggregator { /** * Given a collection of tasks, an aggregator maps these tasks to the aggregated answers. * * @param tasks tasks. * @return Aggregated answers. */ @Nonnull
Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks);
mtsar/mtsar
src/main/java/mtsar/api/validation/TaskAnswerValidation.java
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import io.dropwizard.validation.ValidationMethod; import mtsar.api.Answer; import mtsar.api.Task; import org.inferred.freebuilder.FreeBuilder; import java.util.ArrayList; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.validation; @FreeBuilder public interface TaskAnswerValidation {
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/validation/TaskAnswerValidation.java import io.dropwizard.validation.ValidationMethod; import mtsar.api.Answer; import mtsar.api.Task; import org.inferred.freebuilder.FreeBuilder; import java.util.ArrayList; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.validation; @FreeBuilder public interface TaskAnswerValidation {
Task getTask();
mtsar/mtsar
src/main/java/mtsar/api/validation/TaskAnswerValidation.java
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import io.dropwizard.validation.ValidationMethod; import mtsar.api.Answer; import mtsar.api.Task; import org.inferred.freebuilder.FreeBuilder; import java.util.ArrayList; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.validation; @FreeBuilder public interface TaskAnswerValidation { Task getTask();
// Path: src/main/java/mtsar/api/Answer.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Answer.Builder.class) // public interface Answer { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // Integer getWorkerId(); // // @JsonProperty // Integer getTaskId(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // default Optional<String> getAnswer() { // if (getAnswers().isEmpty()) return Optional.empty(); // return Optional.of(getAnswers().get(0)); // } // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Answer_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // setType(AnswerDAO.ANSWER_TYPE_DEFAULT); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Answer build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // // Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/validation/TaskAnswerValidation.java import io.dropwizard.validation.ValidationMethod; import mtsar.api.Answer; import mtsar.api.Task; import org.inferred.freebuilder.FreeBuilder; import java.util.ArrayList; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.validation; @FreeBuilder public interface TaskAnswerValidation { Task getTask();
Answer getAnswer();
mtsar/mtsar
src/main/java/mtsar/api/Worker.java
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @FreeBuilder @XmlRootElement @JsonDeserialize(builder = Worker.Builder.class) public interface Worker { @Nullable @JsonProperty Integer getId(); @JsonProperty String getStage(); @JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Worker_Builder { public Builder() {
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Worker.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @FreeBuilder @XmlRootElement @JsonDeserialize(builder = Worker.Builder.class) public interface Worker { @Nullable @JsonProperty Integer getId(); @JsonProperty String getStage(); @JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Worker_Builder { public Builder() {
setDateTime(DateTimeUtils.now());
mtsar/mtsar
src/main/java/mtsar/api/Worker.java
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @FreeBuilder @XmlRootElement @JsonDeserialize(builder = Worker.Builder.class) public interface Worker { @Nullable @JsonProperty Integer getId(); @JsonProperty String getStage(); @JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Worker_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setMetadata(String json) {
// Path: src/main/java/mtsar/util/DateTimeUtils.java // public final class DateTimeUtils { // @Nonnull // public static Timestamp now() { // return Timestamp.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); // } // } // // Path: src/main/java/mtsar/util/PostgresUtils.java // public class PostgresUtils { // public final static TypeReference<Map<String, String>> MAP_STRING_TO_STRING = new TypeReference<Map<String, String>>() { // }; // // public static String buildArrayString(@Nonnull Collection<String> elements) { // requireNonNull(elements); // return buildArrayString(elements.toArray(new String[elements.size()])); // } // // public static String buildArrayString(@Nonnull String[] elements) { // requireNonNull(elements); // final StringBuilder sb = new StringBuilder("{"); // for (int i = 0, len = elements.length; i < len; i++) { // if (i > 0) sb.append(','); // final String element = elements[i]; // if (element != null) { // PgArray.escapeArrayElement(sb, element); // } else { // sb.append("NULL"); // } // } // return sb.append('}').toString(); // } // // public static String buildJSONString(@Nonnull Map<String, String> elements) { // requireNonNull(elements); // try { // return new ObjectMapper().writeValueAsString(elements); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // public static Map<String, String> parseJSONString(@Nonnull String json) { // requireNonNull(json); // try { // return new ObjectMapper().readValue(json, MAP_STRING_TO_STRING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/mtsar/api/Worker.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import mtsar.util.DateTimeUtils; import mtsar.util.PostgresUtils; import org.inferred.freebuilder.FreeBuilder; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; import java.util.Map; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api; @FreeBuilder @XmlRootElement @JsonDeserialize(builder = Worker.Builder.class) public interface Worker { @Nullable @JsonProperty Integer getId(); @JsonProperty String getStage(); @JsonProperty Timestamp getDateTime(); @JsonProperty List<String> getTags(); @JsonIgnore Map<String, String> getMetadata(); @JsonIgnore String getTagsTextArray(); @JsonIgnore String getMetadataJSON(); @JsonPOJOBuilder(withPrefix = "set") class Builder extends Worker_Builder { public Builder() { setDateTime(DateTimeUtils.now()); } public Builder setMetadata(String json) {
return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json));
mtsar/mtsar
src/main/java/mtsar/processors/WorkerRanker.java
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import mtsar.api.Worker; import mtsar.api.WorkerRanking; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface WorkerRanker { /** * Given a collection of workers, estimate their performance. * * @param workers workers. * @return Worker rankings. */ @Nonnull
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/processors/WorkerRanker.java import mtsar.api.Worker; import mtsar.api.WorkerRanking; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.processors; public interface WorkerRanker { /** * Given a collection of workers, estimate their performance. * * @param workers workers. * @return Worker rankings. */ @Nonnull
Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers);
mtsar/mtsar
src/main/java/mtsar/api/sql/TaskDAO.java
// Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // }
import mtsar.api.Task; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(TaskDAO.Mapper.class) public interface TaskDAO { String TASK_TYPE_SINGLE = "single"; @SqlQuery("select * from tasks where stage = :stage")
// Path: src/main/java/mtsar/api/Task.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Task.Builder.class) // public interface Task { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonProperty // String getType(); // // @JsonProperty // String getDescription(); // // @JsonProperty // List<String> getAnswers(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonIgnore // String getAnswersTextArray(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Task_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Task build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // setAnswersTextArray(PostgresUtils.buildArrayString(getAnswers())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/sql/TaskDAO.java import mtsar.api.Task; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(TaskDAO.Mapper.class) public interface TaskDAO { String TASK_TYPE_SINGLE = "single"; @SqlQuery("select * from tasks where stage = :stage")
List<Task> listForStage(@Bind("stage") String stage);
mtsar/mtsar
src/test/java/mtsar/ApplicationTest.java
// Path: src/main/java/mtsar/dropwizard/MechanicalTsarApplication.java // public class MechanicalTsarApplication extends Application<MechanicalTsarConfiguration> { // private ApplicationBinder binder; // // public ServiceLocator getLocator() { // return binder.getLocator(); // } // // public static void main(String[] args) throws Exception { // new MechanicalTsarApplication().run(args); // } // // @Override // public String getName() { // return "Mechanical Tsar"; // } // // @Override // public void initialize(Bootstrap<MechanicalTsarConfiguration> bootstrap) { // bootstrap.addBundle(new MechanicalTsarMigrationsBundle()); // // bootstrap.addBundle(new MultiPartBundle()); // bootstrap.addBundle(new AssetsBundle("/mtsar/stylesheets", "/stylesheets", null, "stylesheets")); // bootstrap.addBundle(new AssetsBundle("/mtsar/javascripts", "/javascripts", null, "javascripts")); // bootstrap.addBundle(new AssetsBundle("/mtsar/images", "/images", null, "images")); // bootstrap.addBundle(new AssetsBundle("/mtsar/favicon.ico", "/favicon.ico", null, "favicon")); // bootstrap.addBundle(new AssetsBundle("/mtsar/robots.txt", "/robots.txt", null, "robots")); // bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/assets", null, "assets")); // bootstrap.addBundle(new ViewBundle<>()); // // bootstrap.addCommand(new EvaluateCommand(this)); // bootstrap.addCommand(new SimulateCommand(this)); // bootstrap.addCommand(new ConsoleCommand(this)); // bootstrap.addCommand(new AboutCommand(this)); // } // // @Override // public void run(MechanicalTsarConfiguration configuration, Environment environment) throws ClassNotFoundException { // binder = new ApplicationBinder(configuration, environment); // // final FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,PATCH,DELETE,OPTIONS"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); // filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // filter.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); // // environment.jersey().disable(ServerProperties.WADL_FEATURE_DISABLE); // environment.jersey().register(new ValidatorBinder(environment)); // environment.jersey().register(requireNonNull(getLocator().getService(MetaResource.class))); // environment.jersey().register(requireNonNull(getLocator().getService(StageResource.class))); // // environment.healthChecks().register("version", requireNonNull(getLocator().getService(MechanicalTsarVersionHealthCheck.class))); // } // // public Map<String, Stage> getStages() { // return binder.getStages(); // } // // private static class MechanicalTsarMigrationsBundle extends MigrationsBundle<MechanicalTsarConfiguration> { // @Override // public DataSourceFactory getDataSourceFactory(MechanicalTsarConfiguration configuration) { // return configuration.getDataSourceFactory(); // } // } // // static class ValidatorBinder extends AbstractBinder { // private final Environment environment; // // public ValidatorBinder(Environment environment) { // this.environment = environment; // } // // @Override // protected void configure() { // bind(environment.getValidator()).to(Validator.class); // } // } // } // // Path: src/main/java/mtsar/dropwizard/MechanicalTsarConfiguration.java // public class MechanicalTsarConfiguration extends Configuration { // @Valid // @NotNull // @JsonProperty // private final DataSourceFactory database = new DataSourceFactory(); // // public DataSourceFactory getDataSourceFactory() { // return database; // } // }
import io.dropwizard.testing.junit.DropwizardAppRule; import mtsar.dropwizard.MechanicalTsarApplication; import mtsar.dropwizard.MechanicalTsarConfiguration; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.client.JerseyClientBuilder; import org.junit.ClassRule; import org.junit.Test; import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ApplicationTest { private static final String TEST_YAML_ENV = "MTSAR_TEST_YAML"; private static final String TEST_YAML = "test.yml"; @ClassRule
// Path: src/main/java/mtsar/dropwizard/MechanicalTsarApplication.java // public class MechanicalTsarApplication extends Application<MechanicalTsarConfiguration> { // private ApplicationBinder binder; // // public ServiceLocator getLocator() { // return binder.getLocator(); // } // // public static void main(String[] args) throws Exception { // new MechanicalTsarApplication().run(args); // } // // @Override // public String getName() { // return "Mechanical Tsar"; // } // // @Override // public void initialize(Bootstrap<MechanicalTsarConfiguration> bootstrap) { // bootstrap.addBundle(new MechanicalTsarMigrationsBundle()); // // bootstrap.addBundle(new MultiPartBundle()); // bootstrap.addBundle(new AssetsBundle("/mtsar/stylesheets", "/stylesheets", null, "stylesheets")); // bootstrap.addBundle(new AssetsBundle("/mtsar/javascripts", "/javascripts", null, "javascripts")); // bootstrap.addBundle(new AssetsBundle("/mtsar/images", "/images", null, "images")); // bootstrap.addBundle(new AssetsBundle("/mtsar/favicon.ico", "/favicon.ico", null, "favicon")); // bootstrap.addBundle(new AssetsBundle("/mtsar/robots.txt", "/robots.txt", null, "robots")); // bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/assets", null, "assets")); // bootstrap.addBundle(new ViewBundle<>()); // // bootstrap.addCommand(new EvaluateCommand(this)); // bootstrap.addCommand(new SimulateCommand(this)); // bootstrap.addCommand(new ConsoleCommand(this)); // bootstrap.addCommand(new AboutCommand(this)); // } // // @Override // public void run(MechanicalTsarConfiguration configuration, Environment environment) throws ClassNotFoundException { // binder = new ApplicationBinder(configuration, environment); // // final FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,PATCH,DELETE,OPTIONS"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); // filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // filter.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); // // environment.jersey().disable(ServerProperties.WADL_FEATURE_DISABLE); // environment.jersey().register(new ValidatorBinder(environment)); // environment.jersey().register(requireNonNull(getLocator().getService(MetaResource.class))); // environment.jersey().register(requireNonNull(getLocator().getService(StageResource.class))); // // environment.healthChecks().register("version", requireNonNull(getLocator().getService(MechanicalTsarVersionHealthCheck.class))); // } // // public Map<String, Stage> getStages() { // return binder.getStages(); // } // // private static class MechanicalTsarMigrationsBundle extends MigrationsBundle<MechanicalTsarConfiguration> { // @Override // public DataSourceFactory getDataSourceFactory(MechanicalTsarConfiguration configuration) { // return configuration.getDataSourceFactory(); // } // } // // static class ValidatorBinder extends AbstractBinder { // private final Environment environment; // // public ValidatorBinder(Environment environment) { // this.environment = environment; // } // // @Override // protected void configure() { // bind(environment.getValidator()).to(Validator.class); // } // } // } // // Path: src/main/java/mtsar/dropwizard/MechanicalTsarConfiguration.java // public class MechanicalTsarConfiguration extends Configuration { // @Valid // @NotNull // @JsonProperty // private final DataSourceFactory database = new DataSourceFactory(); // // public DataSourceFactory getDataSourceFactory() { // return database; // } // } // Path: src/test/java/mtsar/ApplicationTest.java import io.dropwizard.testing.junit.DropwizardAppRule; import mtsar.dropwizard.MechanicalTsarApplication; import mtsar.dropwizard.MechanicalTsarConfiguration; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.client.JerseyClientBuilder; import org.junit.ClassRule; import org.junit.Test; import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ApplicationTest { private static final String TEST_YAML_ENV = "MTSAR_TEST_YAML"; private static final String TEST_YAML = "test.yml"; @ClassRule
public static final DropwizardAppRule<MechanicalTsarConfiguration> RULE = new DropwizardAppRule<>(MechanicalTsarApplication.class, StringUtils.defaultString(System.getenv(TEST_YAML_ENV), TEST_YAML));
mtsar/mtsar
src/test/java/mtsar/ApplicationTest.java
// Path: src/main/java/mtsar/dropwizard/MechanicalTsarApplication.java // public class MechanicalTsarApplication extends Application<MechanicalTsarConfiguration> { // private ApplicationBinder binder; // // public ServiceLocator getLocator() { // return binder.getLocator(); // } // // public static void main(String[] args) throws Exception { // new MechanicalTsarApplication().run(args); // } // // @Override // public String getName() { // return "Mechanical Tsar"; // } // // @Override // public void initialize(Bootstrap<MechanicalTsarConfiguration> bootstrap) { // bootstrap.addBundle(new MechanicalTsarMigrationsBundle()); // // bootstrap.addBundle(new MultiPartBundle()); // bootstrap.addBundle(new AssetsBundle("/mtsar/stylesheets", "/stylesheets", null, "stylesheets")); // bootstrap.addBundle(new AssetsBundle("/mtsar/javascripts", "/javascripts", null, "javascripts")); // bootstrap.addBundle(new AssetsBundle("/mtsar/images", "/images", null, "images")); // bootstrap.addBundle(new AssetsBundle("/mtsar/favicon.ico", "/favicon.ico", null, "favicon")); // bootstrap.addBundle(new AssetsBundle("/mtsar/robots.txt", "/robots.txt", null, "robots")); // bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/assets", null, "assets")); // bootstrap.addBundle(new ViewBundle<>()); // // bootstrap.addCommand(new EvaluateCommand(this)); // bootstrap.addCommand(new SimulateCommand(this)); // bootstrap.addCommand(new ConsoleCommand(this)); // bootstrap.addCommand(new AboutCommand(this)); // } // // @Override // public void run(MechanicalTsarConfiguration configuration, Environment environment) throws ClassNotFoundException { // binder = new ApplicationBinder(configuration, environment); // // final FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,PATCH,DELETE,OPTIONS"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); // filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // filter.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); // // environment.jersey().disable(ServerProperties.WADL_FEATURE_DISABLE); // environment.jersey().register(new ValidatorBinder(environment)); // environment.jersey().register(requireNonNull(getLocator().getService(MetaResource.class))); // environment.jersey().register(requireNonNull(getLocator().getService(StageResource.class))); // // environment.healthChecks().register("version", requireNonNull(getLocator().getService(MechanicalTsarVersionHealthCheck.class))); // } // // public Map<String, Stage> getStages() { // return binder.getStages(); // } // // private static class MechanicalTsarMigrationsBundle extends MigrationsBundle<MechanicalTsarConfiguration> { // @Override // public DataSourceFactory getDataSourceFactory(MechanicalTsarConfiguration configuration) { // return configuration.getDataSourceFactory(); // } // } // // static class ValidatorBinder extends AbstractBinder { // private final Environment environment; // // public ValidatorBinder(Environment environment) { // this.environment = environment; // } // // @Override // protected void configure() { // bind(environment.getValidator()).to(Validator.class); // } // } // } // // Path: src/main/java/mtsar/dropwizard/MechanicalTsarConfiguration.java // public class MechanicalTsarConfiguration extends Configuration { // @Valid // @NotNull // @JsonProperty // private final DataSourceFactory database = new DataSourceFactory(); // // public DataSourceFactory getDataSourceFactory() { // return database; // } // }
import io.dropwizard.testing.junit.DropwizardAppRule; import mtsar.dropwizard.MechanicalTsarApplication; import mtsar.dropwizard.MechanicalTsarConfiguration; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.client.JerseyClientBuilder; import org.junit.ClassRule; import org.junit.Test; import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ApplicationTest { private static final String TEST_YAML_ENV = "MTSAR_TEST_YAML"; private static final String TEST_YAML = "test.yml"; @ClassRule
// Path: src/main/java/mtsar/dropwizard/MechanicalTsarApplication.java // public class MechanicalTsarApplication extends Application<MechanicalTsarConfiguration> { // private ApplicationBinder binder; // // public ServiceLocator getLocator() { // return binder.getLocator(); // } // // public static void main(String[] args) throws Exception { // new MechanicalTsarApplication().run(args); // } // // @Override // public String getName() { // return "Mechanical Tsar"; // } // // @Override // public void initialize(Bootstrap<MechanicalTsarConfiguration> bootstrap) { // bootstrap.addBundle(new MechanicalTsarMigrationsBundle()); // // bootstrap.addBundle(new MultiPartBundle()); // bootstrap.addBundle(new AssetsBundle("/mtsar/stylesheets", "/stylesheets", null, "stylesheets")); // bootstrap.addBundle(new AssetsBundle("/mtsar/javascripts", "/javascripts", null, "javascripts")); // bootstrap.addBundle(new AssetsBundle("/mtsar/images", "/images", null, "images")); // bootstrap.addBundle(new AssetsBundle("/mtsar/favicon.ico", "/favicon.ico", null, "favicon")); // bootstrap.addBundle(new AssetsBundle("/mtsar/robots.txt", "/robots.txt", null, "robots")); // bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/assets", null, "assets")); // bootstrap.addBundle(new ViewBundle<>()); // // bootstrap.addCommand(new EvaluateCommand(this)); // bootstrap.addCommand(new SimulateCommand(this)); // bootstrap.addCommand(new ConsoleCommand(this)); // bootstrap.addCommand(new AboutCommand(this)); // } // // @Override // public void run(MechanicalTsarConfiguration configuration, Environment environment) throws ClassNotFoundException { // binder = new ApplicationBinder(configuration, environment); // // final FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,PATCH,DELETE,OPTIONS"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); // filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // filter.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location"); // filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); // // environment.jersey().disable(ServerProperties.WADL_FEATURE_DISABLE); // environment.jersey().register(new ValidatorBinder(environment)); // environment.jersey().register(requireNonNull(getLocator().getService(MetaResource.class))); // environment.jersey().register(requireNonNull(getLocator().getService(StageResource.class))); // // environment.healthChecks().register("version", requireNonNull(getLocator().getService(MechanicalTsarVersionHealthCheck.class))); // } // // public Map<String, Stage> getStages() { // return binder.getStages(); // } // // private static class MechanicalTsarMigrationsBundle extends MigrationsBundle<MechanicalTsarConfiguration> { // @Override // public DataSourceFactory getDataSourceFactory(MechanicalTsarConfiguration configuration) { // return configuration.getDataSourceFactory(); // } // } // // static class ValidatorBinder extends AbstractBinder { // private final Environment environment; // // public ValidatorBinder(Environment environment) { // this.environment = environment; // } // // @Override // protected void configure() { // bind(environment.getValidator()).to(Validator.class); // } // } // } // // Path: src/main/java/mtsar/dropwizard/MechanicalTsarConfiguration.java // public class MechanicalTsarConfiguration extends Configuration { // @Valid // @NotNull // @JsonProperty // private final DataSourceFactory database = new DataSourceFactory(); // // public DataSourceFactory getDataSourceFactory() { // return database; // } // } // Path: src/test/java/mtsar/ApplicationTest.java import io.dropwizard.testing.junit.DropwizardAppRule; import mtsar.dropwizard.MechanicalTsarApplication; import mtsar.dropwizard.MechanicalTsarConfiguration; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.client.JerseyClientBuilder; import org.junit.ClassRule; import org.junit.Test; import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar; public class ApplicationTest { private static final String TEST_YAML_ENV = "MTSAR_TEST_YAML"; private static final String TEST_YAML = "test.yml"; @ClassRule
public static final DropwizardAppRule<MechanicalTsarConfiguration> RULE = new DropwizardAppRule<>(MechanicalTsarApplication.class, StringUtils.defaultString(System.getenv(TEST_YAML_ENV), TEST_YAML));
mtsar/mtsar
src/main/java/mtsar/api/sql/WorkerDAO.java
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import mtsar.api.Worker; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(WorkerDAO.Mapper.class) public interface WorkerDAO { @SqlQuery("select * from workers where stage = :stage")
// Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/sql/WorkerDAO.java import mtsar.api.Worker; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import java.util.List; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.sql; @UseStringTemplate3StatementLocator @RegisterMapper(WorkerDAO.Mapper.class) public interface WorkerDAO { @SqlQuery("select * from workers where stage = :stage")
List<Worker> listForStage(@Bind("stage") String stage);
mtsar/mtsar
src/main/java/mtsar/api/csv/WorkerCSV.java
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import java.util.*; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Sets; import mtsar.api.Stage; import mtsar.api.Worker; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.sql.Timestamp;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class WorkerCSV { public static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"id", "stage", "datetime", "tags"};
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/csv/WorkerCSV.java import java.util.*; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Sets; import mtsar.api.Stage; import mtsar.api.Worker; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class WorkerCSV { public static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"id", "stage", "datetime", "tags"};
private static final Comparator<Worker> ORDER = (w1, w2) -> w1.getId().compareTo(w2.getId());
mtsar/mtsar
src/main/java/mtsar/api/csv/WorkerCSV.java
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // }
import java.util.*; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Sets; import mtsar.api.Stage; import mtsar.api.Worker; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.sql.Timestamp;
/* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class WorkerCSV { public static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"id", "stage", "datetime", "tags"}; private static final Comparator<Worker> ORDER = (w1, w2) -> w1.getId().compareTo(w2.getId());
// Path: src/main/java/mtsar/api/Stage.java // @XmlRootElement // public class Stage { // private final Definition definition; // private final WorkerRanker workerRanker; // private final TaskAllocator taskAllocator; // private final AnswerAggregator answerAggregator; // // @Inject // public Stage(Definition definition, WorkerRanker workerRanker, TaskAllocator taskAllocator, AnswerAggregator answerAggregator) { // this.definition = requireNonNull(definition); // this.workerRanker = requireNonNull(workerRanker); // this.taskAllocator = requireNonNull(taskAllocator); // this.answerAggregator = requireNonNull(answerAggregator); // } // // @JsonProperty // public String getId() { // return definition.getId(); // } // // @JsonProperty // public String getDescription() { // return definition.getDescription(); // } // // @JsonProperty // public Map<String, String> getOptions() { // return definition.getOptions(); // } // // @JsonIgnore // public WorkerRanker getWorkerRanker() { // return workerRanker; // } // // @JsonIgnore // public TaskAllocator getTaskAllocator() { // return taskAllocator; // } // // @JsonIgnore // public AnswerAggregator getAnswerAggregator() { // return answerAggregator; // } // // @JsonProperty("workerRanker") // @SuppressWarnings("unused") // public String getWorkerRankerName() { // return definition.getWorkerRanker(); // } // // @JsonProperty("taskAllocator") // @SuppressWarnings("unused") // public String getTaskAllocatorName() { // return definition.getTaskAllocator(); // } // // @JsonProperty("answerAggregator") // @SuppressWarnings("unused") // public String getAnswerAggregatorName() { // return definition.getAnswerAggregator(); // } // // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Definition.Builder.class) // public interface Definition { // @JsonProperty // String getId(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // String getDescription(); // // @JsonProperty() // String getWorkerRanker(); // // @JsonProperty() // String getTaskAllocator(); // // @JsonProperty() // String getAnswerAggregator(); // // @JsonProperty // Map<String, String> getOptions(); // // @JsonIgnore // String getOptionsJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Stage_Definition_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setOptions(String json) { // return putAllOptions(PostgresUtils.parseJSONString(json)); // } // // @Override // public Definition build() { // setOptionsJSON(PostgresUtils.buildJSONString(getOptions())); // return super.build(); // } // } // } // } // // Path: src/main/java/mtsar/api/Worker.java // @FreeBuilder // @XmlRootElement // @JsonDeserialize(builder = Worker.Builder.class) // public interface Worker { // @Nullable // @JsonProperty // Integer getId(); // // @JsonProperty // String getStage(); // // @JsonProperty // Timestamp getDateTime(); // // @JsonProperty // List<String> getTags(); // // @JsonIgnore // Map<String, String> getMetadata(); // // @JsonIgnore // String getTagsTextArray(); // // @JsonIgnore // String getMetadataJSON(); // // @JsonPOJOBuilder(withPrefix = "set") // class Builder extends Worker_Builder { // public Builder() { // setDateTime(DateTimeUtils.now()); // } // // public Builder setMetadata(String json) { // return setMetadataJSON(json).putAllMetadata(PostgresUtils.parseJSONString(json)); // } // // public Worker build() { // setTagsTextArray(PostgresUtils.buildArrayString(getTags())); // setMetadataJSON(PostgresUtils.buildJSONString(getMetadata())); // return super.build(); // } // } // } // Path: src/main/java/mtsar/api/csv/WorkerCSV.java import java.util.*; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Sets; import mtsar.api.Stage; import mtsar.api.Worker; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; /* * Copyright 2015 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mtsar.api.csv; public final class WorkerCSV { public static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader(); private static final String[] HEADER = {"id", "stage", "datetime", "tags"}; private static final Comparator<Worker> ORDER = (w1, w2) -> w1.getId().compareTo(w2.getId());
public static Iterator<Worker> parse(Stage stage, CSVParser csv) {
gcewing/SGCraft
src/mod/gcewing/sg/cc/CCSGPeripheral.java
// Path: src/mod/gcewing/sg/SGInterfaceTE.java // public static class CIStargateState { // public String state; // public int chevrons; // public String direction; // public CIStargateState(String state, int chevrons, String direction) { // this.state = state; // this.chevrons = chevrons; // this.direction = direction; // } // }
import com.google.common.base.Joiner; import net.minecraft.tileentity.*; import net.minecraft.world.*; import net.minecraftforge.common.util.*; import dan200.computercraft.api.lua.*; import dan200.computercraft.api.peripheral.*; import gcewing.sg.*; import gcewing.sg.SGInterfaceTE.CIStargateState;
//------------------------------------------------------------------------------------------------ // // SG Craft - Computercraft Interface Peripheral // //------------------------------------------------------------------------------------------------ package gcewing.sg.cc; public class CCSGPeripheral implements IPeripheral { static CCMethod[] methods = { new SGMethod("stargateState") { Object[] call(SGInterfaceTE te, Object[] args) {
// Path: src/mod/gcewing/sg/SGInterfaceTE.java // public static class CIStargateState { // public String state; // public int chevrons; // public String direction; // public CIStargateState(String state, int chevrons, String direction) { // this.state = state; // this.chevrons = chevrons; // this.direction = direction; // } // } // Path: src/mod/gcewing/sg/cc/CCSGPeripheral.java import com.google.common.base.Joiner; import net.minecraft.tileentity.*; import net.minecraft.world.*; import net.minecraftforge.common.util.*; import dan200.computercraft.api.lua.*; import dan200.computercraft.api.peripheral.*; import gcewing.sg.*; import gcewing.sg.SGInterfaceTE.CIStargateState; //------------------------------------------------------------------------------------------------ // // SG Craft - Computercraft Interface Peripheral // //------------------------------------------------------------------------------------------------ package gcewing.sg.cc; public class CCSGPeripheral implements IPeripheral { static CCMethod[] methods = { new SGMethod("stargateState") { Object[] call(SGInterfaceTE te, Object[] args) {
CIStargateState result = te.ciStargateState();
gcewing/SGCraft
src/base/gcewing/sg/Trans3.java
// Path: src/base/gcewing/sg/Vector3.java // public static Vec3i getDirectionVec(EnumFacing f) { // return directionVec[f.ordinal()]; // }
import java.util.*; import static java.lang.Math.*; import net.minecraft.entity.Entity; import net.minecraft.util.*; import net.minecraftforge.common.util.*; import static gcewing.sg.Vector3.getDirectionVec;
public Vector3 ip(double x, double y, double z) { return ip(new Vector3(x, y, z)); } public Vector3 ip(Vector3 u) { return rotation.imul(u.sub(offset)).mul(1.0/scaling); } public Vector3 v(double x, double y, double z) { return v(new Vector3(x, y, z)); } public Vector3 iv(double x, double y, double z) { return iv(new Vector3(x, y, z)); } public Vector3 v(Vec3i u) { return v(u.getX(), u.getY(), u.getZ()); } public Vector3 iv(Vec3i u) { return iv(u.getX(), u.getY(), u.getZ()); } public Vector3 v(Vector3 u) { return rotation.mul(u.mul(scaling)); } public Vector3 v(EnumFacing f) {
// Path: src/base/gcewing/sg/Vector3.java // public static Vec3i getDirectionVec(EnumFacing f) { // return directionVec[f.ordinal()]; // } // Path: src/base/gcewing/sg/Trans3.java import java.util.*; import static java.lang.Math.*; import net.minecraft.entity.Entity; import net.minecraft.util.*; import net.minecraftforge.common.util.*; import static gcewing.sg.Vector3.getDirectionVec; public Vector3 ip(double x, double y, double z) { return ip(new Vector3(x, y, z)); } public Vector3 ip(Vector3 u) { return rotation.imul(u.sub(offset)).mul(1.0/scaling); } public Vector3 v(double x, double y, double z) { return v(new Vector3(x, y, z)); } public Vector3 iv(double x, double y, double z) { return iv(new Vector3(x, y, z)); } public Vector3 v(Vec3i u) { return v(u.getX(), u.getY(), u.getZ()); } public Vector3 iv(Vec3i u) { return iv(u.getX(), u.getY(), u.getZ()); } public Vector3 v(Vector3 u) { return rotation.mul(u.mul(scaling)); } public Vector3 v(EnumFacing f) {
return v(getDirectionVec(f));