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
pinaraf/ebics
src/main/java/org/kopi/ebics/xml/HPBResponseOrderDataElement.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // }
import org.kopi.ebics.schema.h003.HPBResponseOrderDataType; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.schema.h003.HPBResponseOrderDataDocument;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>HPBResponseOrderDataElement</code> contains the public bank * keys in encrypted mode. The user should decrypt with his encryption * key to have the bank public keys. * * @author hachani * */ public class HPBResponseOrderDataElement extends DefaultResponseElement { /** * Creates a new <code>HPBResponseOrderDataElement</code> from a given * content factory. * @param factory the content factory. */ public HPBResponseOrderDataElement(ContentFactory factory) { super(factory, "HPBData"); } /** * Returns the authentication bank certificate. * @return the authentication bank certificate. */ public byte[] getBankX002Certificate() { return response.getAuthenticationPubKeyInfo().getX509Data().getX509CertificateArray(0); } /** * Returns the encryption bank certificate. * @return the encryption bank certificate. */ public byte[] getBankE002Certificate() { return response.getEncryptionPubKeyInfo().getX509Data().getX509CertificateArray(0); } public byte[] getBankE002PublicKeyModulus() { return response.getEncryptionPubKeyInfo().getPubKeyValue().getRSAKeyValue().getModulus(); } public byte[] getBankE002PublicKeyExponent() { return response.getEncryptionPubKeyInfo().getPubKeyValue().getRSAKeyValue().getExponent(); } public byte[] getBankX002PublicKeyModulus() { return response.getAuthenticationPubKeyInfo().getPubKeyValue().getRSAKeyValue().getModulus(); } public byte[] getBankX002PublicKeyExponent() { return response.getAuthenticationPubKeyInfo().getPubKeyValue().getRSAKeyValue().getExponent(); } @Override
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // Path: src/main/java/org/kopi/ebics/xml/HPBResponseOrderDataElement.java import org.kopi.ebics.schema.h003.HPBResponseOrderDataType; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.schema.h003.HPBResponseOrderDataDocument; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>HPBResponseOrderDataElement</code> contains the public bank * keys in encrypted mode. The user should decrypt with his encryption * key to have the bank public keys. * * @author hachani * */ public class HPBResponseOrderDataElement extends DefaultResponseElement { /** * Creates a new <code>HPBResponseOrderDataElement</code> from a given * content factory. * @param factory the content factory. */ public HPBResponseOrderDataElement(ContentFactory factory) { super(factory, "HPBData"); } /** * Returns the authentication bank certificate. * @return the authentication bank certificate. */ public byte[] getBankX002Certificate() { return response.getAuthenticationPubKeyInfo().getX509Data().getX509CertificateArray(0); } /** * Returns the encryption bank certificate. * @return the encryption bank certificate. */ public byte[] getBankE002Certificate() { return response.getEncryptionPubKeyInfo().getX509Data().getX509CertificateArray(0); } public byte[] getBankE002PublicKeyModulus() { return response.getEncryptionPubKeyInfo().getPubKeyValue().getRSAKeyValue().getModulus(); } public byte[] getBankE002PublicKeyExponent() { return response.getEncryptionPubKeyInfo().getPubKeyValue().getRSAKeyValue().getExponent(); } public byte[] getBankX002PublicKeyModulus() { return response.getAuthenticationPubKeyInfo().getPubKeyValue().getRSAKeyValue().getModulus(); } public byte[] getBankX002PublicKeyExponent() { return response.getAuthenticationPubKeyInfo().getPubKeyValue().getRSAKeyValue().getExponent(); } @Override
public void build() throws EbicsException {
pinaraf/ebics
src/main/java/org/kopi/ebics/client/HttpRequestSender.java
// Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/EbicsSession.java // public class EbicsSession { // // /** // * Constructs a new ebics session // * @param user the ebics user // * @param the ebics client configuration // */ // public EbicsSession(EbicsUser user, Configuration configuration) { // this.user = user; // this.configuration = configuration; // parameters = new HashMap<String, String>(); // } // // /** // * Returns the banks encryption key. // * The key will be fetched automatically form the bank if needed. // * @return the banks encryption key. // * @throws IOException Communication error during key retrieval. // * @throws EbicsException Server error message generated during key retrieval. // */ // public RSAPublicKey getBankE002Key() throws IOException, EbicsException { // return user.getPartner().getBank().getE002Key(); // } // // /** // * Returns the banks authentication key. // * The key will be fetched automatically form the bank if needed. // * @return the banks authentication key. // * @throws IOException Communication error during key retrieval. // * @throws EbicsException Server error message generated during key retrieval. // */ // public RSAPublicKey getBankX002Key() throws IOException, EbicsException { // return user.getPartner().getBank().getX002Key(); // } // // /** // * Returns the bank id. // * @return the bank id. // * @throws EbicsException // */ // public String getBankID() throws EbicsException { // return user.getPartner().getBank().getHostId(); // } // // /** // * Return the session user. // * @return the session user. // */ // public EbicsUser getUser() { // return user; // } // // /** // * Returns the client application configuration. // * @return the client application configuration. // */ // public Configuration getConfiguration() { // return configuration; // } // // /** // * Sets the optional product identification that will be sent to the bank during each request. // * @param product Product description // */ // public void setProduct(Product product) { // this.product = product; // } // // /** // * @return the product // */ // public Product getProduct() { // return product; // } // // /** // * Adds a session parameter to use it in the transfer process. // * @param key the parameter key // * @param value the parameter value // */ // public void addSessionParam(String key, String value) { // parameters.put(key, value); // } // // /** // * Retrieves a session parameter using its key. // * @param key the parameter key // * @return the session parameter // */ // public String getSessionParam(String key) { // if (key == null) { // return null; // } // // return parameters.get(key); // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private EbicsUser user; // private Configuration configuration; // private Product product; // private Map<String, String> parameters; // }
import org.kopi.ebics.io.InputStreamContentFactory; import org.kopi.ebics.session.EbicsSession; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.kopi.ebics.interfaces.ContentFactory;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.client; /** * A simple HTTP request sender and receiver. * The send returns a HTTP code that should be analyzed * before proceeding ebics request response parse. * * @author hachani * */ public class HttpRequestSender { /** * Constructs a new <code>HttpRequestSender</code> with a * given ebics session. * @param session the ebics session */ public HttpRequestSender(EbicsSession session) { this.session = session; } /** * Sends the request contained in the <code>ContentFactory</code>. * The <code>ContentFactory</code> will deliver the request as * an <code>InputStream</code>. * * @param request the ebics request * @return the HTTP return code */
// Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/EbicsSession.java // public class EbicsSession { // // /** // * Constructs a new ebics session // * @param user the ebics user // * @param the ebics client configuration // */ // public EbicsSession(EbicsUser user, Configuration configuration) { // this.user = user; // this.configuration = configuration; // parameters = new HashMap<String, String>(); // } // // /** // * Returns the banks encryption key. // * The key will be fetched automatically form the bank if needed. // * @return the banks encryption key. // * @throws IOException Communication error during key retrieval. // * @throws EbicsException Server error message generated during key retrieval. // */ // public RSAPublicKey getBankE002Key() throws IOException, EbicsException { // return user.getPartner().getBank().getE002Key(); // } // // /** // * Returns the banks authentication key. // * The key will be fetched automatically form the bank if needed. // * @return the banks authentication key. // * @throws IOException Communication error during key retrieval. // * @throws EbicsException Server error message generated during key retrieval. // */ // public RSAPublicKey getBankX002Key() throws IOException, EbicsException { // return user.getPartner().getBank().getX002Key(); // } // // /** // * Returns the bank id. // * @return the bank id. // * @throws EbicsException // */ // public String getBankID() throws EbicsException { // return user.getPartner().getBank().getHostId(); // } // // /** // * Return the session user. // * @return the session user. // */ // public EbicsUser getUser() { // return user; // } // // /** // * Returns the client application configuration. // * @return the client application configuration. // */ // public Configuration getConfiguration() { // return configuration; // } // // /** // * Sets the optional product identification that will be sent to the bank during each request. // * @param product Product description // */ // public void setProduct(Product product) { // this.product = product; // } // // /** // * @return the product // */ // public Product getProduct() { // return product; // } // // /** // * Adds a session parameter to use it in the transfer process. // * @param key the parameter key // * @param value the parameter value // */ // public void addSessionParam(String key, String value) { // parameters.put(key, value); // } // // /** // * Retrieves a session parameter using its key. // * @param key the parameter key // * @return the session parameter // */ // public String getSessionParam(String key) { // if (key == null) { // return null; // } // // return parameters.get(key); // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private EbicsUser user; // private Configuration configuration; // private Product product; // private Map<String, String> parameters; // } // Path: src/main/java/org/kopi/ebics/client/HttpRequestSender.java import org.kopi.ebics.io.InputStreamContentFactory; import org.kopi.ebics.session.EbicsSession; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.kopi.ebics.interfaces.ContentFactory; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.client; /** * A simple HTTP request sender and receiver. * The send returns a HTTP code that should be analyzed * before proceeding ebics request response parse. * * @author hachani * */ public class HttpRequestSender { /** * Constructs a new <code>HttpRequestSender</code> with a * given ebics session. * @param session the ebics session */ public HttpRequestSender(EbicsSession session) { this.session = session; } /** * Sends the request contained in the <code>ContentFactory</code>. * The <code>ContentFactory</code> will deliver the request as * an <code>InputStream</code>. * * @param request the ebics request * @return the HTTP return code */
public final int send(ContentFactory request) throws IOException {
pinaraf/ebics
src/main/java/org/kopi/ebics/xml/DTransferResponseElement.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/OrderType.java // public enum OrderType { // HIA, // HAA, // HKD, // HPB, // HPD, // HTD, // INI, // FUL, // FDL, // SPR, // AZV, // C2C, // CCC, // CCT, // CCU, // CD1, // CDB, // CDC, // CDD, // DTE, // EUE, // HAC, // PTK, // STA // }
import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.session.OrderType;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>DTransferResponseElement</code> is the response element * for all ebics downloads transfers. * * @author Hachani * */ public class DTransferResponseElement extends TransferResponseElement { /** * Constructs a new <code>DTransferResponseElement</code> object. * @param factory the content factory * @param orderType the order type * @param name the element name. */ public DTransferResponseElement(ContentFactory factory,
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/OrderType.java // public enum OrderType { // HIA, // HAA, // HKD, // HPB, // HPD, // HTD, // INI, // FUL, // FDL, // SPR, // AZV, // C2C, // CCC, // CCT, // CCU, // CD1, // CDB, // CDC, // CDD, // DTE, // EUE, // HAC, // PTK, // STA // } // Path: src/main/java/org/kopi/ebics/xml/DTransferResponseElement.java import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.session.OrderType; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>DTransferResponseElement</code> is the response element * for all ebics downloads transfers. * * @author Hachani * */ public class DTransferResponseElement extends TransferResponseElement { /** * Constructs a new <code>DTransferResponseElement</code> object. * @param factory the content factory * @param orderType the order type * @param name the element name. */ public DTransferResponseElement(ContentFactory factory,
OrderType orderType,
pinaraf/ebics
src/main/java/org/kopi/ebics/xml/DTransferResponseElement.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/OrderType.java // public enum OrderType { // HIA, // HAA, // HKD, // HPB, // HPD, // HTD, // INI, // FUL, // FDL, // SPR, // AZV, // C2C, // CCC, // CCT, // CCU, // CD1, // CDB, // CDC, // CDD, // DTE, // EUE, // HAC, // PTK, // STA // }
import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.session.OrderType;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>DTransferResponseElement</code> is the response element * for all ebics downloads transfers. * * @author Hachani * */ public class DTransferResponseElement extends TransferResponseElement { /** * Constructs a new <code>DTransferResponseElement</code> object. * @param factory the content factory * @param orderType the order type * @param name the element name. */ public DTransferResponseElement(ContentFactory factory, OrderType orderType, String name) { super(factory, name); } @Override
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // // Path: src/main/java/org/kopi/ebics/session/OrderType.java // public enum OrderType { // HIA, // HAA, // HKD, // HPB, // HPD, // HTD, // INI, // FUL, // FDL, // SPR, // AZV, // C2C, // CCC, // CCT, // CCU, // CD1, // CDB, // CDC, // CDD, // DTE, // EUE, // HAC, // PTK, // STA // } // Path: src/main/java/org/kopi/ebics/xml/DTransferResponseElement.java import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.session.OrderType; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.xml; /** * The <code>DTransferResponseElement</code> is the response element * for all ebics downloads transfers. * * @author Hachani * */ public class DTransferResponseElement extends TransferResponseElement { /** * Constructs a new <code>DTransferResponseElement</code> object. * @param factory the content factory * @param orderType the order type * @param name the element name. */ public DTransferResponseElement(ContentFactory factory, OrderType orderType, String name) { super(factory, name); } @Override
public void build() throws EbicsException {
pinaraf/ebics
src/main/java/org/kopi/ebics/certificate/KeyUtil.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // }
import org.kopi.ebics.exception.EbicsException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.interfaces.RSAPublicKey; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.certificate; /** * Some key utilities * * @author hachani * */ public class KeyUtil { /** * Generates a <code>KeyPair</code> in RSA format. * * @param keyLen - key size * @return KeyPair the key pair * @throws NoSuchAlgorithmException */ public static KeyPair makeKeyPair(int keyLen) throws NoSuchAlgorithmException{ KeyPairGenerator keyGen; keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keyLen, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); return keypair; } /** * Generates a random password * * @return the password */ public static String generatePassword() { SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); String pwd = Base64.encodeBase64String(random.generateSeed(5)); return pwd.substring(0, pwd.length() - 2); } catch (NoSuchAlgorithmException e) { return "changeit"; } } /** * Returns the digest value of a given public key. * * * <p>In Version “H003” of the EBICS protocol the ES of the financial: * * <p>The SHA-256 hash values of the financial institution's public keys for X002 and E002 are * composed by concatenating the exponent with a blank character and the modulus in hexadecimal * representation (using lower case letters) without leading zero (as to the hexadecimal * representation). The resulting string has to be converted into a byte array based on US ASCII * code. * * @param publicKey the public key * @return the digest value * @throws EbicsException */
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // Path: src/main/java/org/kopi/ebics/certificate/KeyUtil.java import org.kopi.ebics.exception.EbicsException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.interfaces.RSAPublicKey; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.certificate; /** * Some key utilities * * @author hachani * */ public class KeyUtil { /** * Generates a <code>KeyPair</code> in RSA format. * * @param keyLen - key size * @return KeyPair the key pair * @throws NoSuchAlgorithmException */ public static KeyPair makeKeyPair(int keyLen) throws NoSuchAlgorithmException{ KeyPairGenerator keyGen; keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keyLen, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); return keypair; } /** * Generates a random password * * @return the password */ public static String generatePassword() { SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); String pwd = Base64.encodeBase64String(random.generateSeed(5)); return pwd.substring(0, pwd.length() - 2); } catch (NoSuchAlgorithmException e) { return "changeit"; } } /** * Returns the digest value of a given public key. * * * <p>In Version “H003” of the EBICS protocol the ES of the financial: * * <p>The SHA-256 hash values of the financial institution's public keys for X002 and E002 are * composed by concatenating the exponent with a blank character and the modulus in hexadecimal * representation (using lower case letters) without leading zero (as to the hexadecimal * representation). The resulting string has to be converted into a byte array based on US ASCII * code. * * @param publicKey the public key * @return the digest value * @throws EbicsException */
public static byte[] getKeyDigest(RSAPublicKey publicKey) throws EbicsException {
pinaraf/ebics
src/main/java/org/kopi/ebics/io/IOUtils.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory;
* @return the created file. */ public static File createFile(File parent, String name) { File file; file = new File(parent, name); return file; } /** * Creates a file from its name. The name can be absolute if * only the directory tree is created * @param name the file name * @return the created file */ public static File createFile(String name) { File file; file = new File(name); return file; } /** * Returns the content of a file as byte array. * @param path the file path * @return the byte array content of the file * @throws EbicsException */
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // Path: src/main/java/org/kopi/ebics/io/IOUtils.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; * @return the created file. */ public static File createFile(File parent, String name) { File file; file = new File(parent, name); return file; } /** * Creates a file from its name. The name can be absolute if * only the directory tree is created * @param name the file name * @return the created file */ public static File createFile(String name) { File file; file = new File(name); return file; } /** * Returns the content of a file as byte array. * @param path the file path * @return the byte array content of the file * @throws EbicsException */
public static byte[] getFileContent(String path) throws EbicsException {
pinaraf/ebics
src/main/java/org/kopi/ebics/io/IOUtils.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory;
return file; } /** * Returns the content of a file as byte array. * @param path the file path * @return the byte array content of the file * @throws EbicsException */ public static byte[] getFileContent(String path) throws EbicsException { try { InputStream input; byte[] content; input = new FileInputStream(path); content = new byte[input.available()]; input.read(content); input.close(); return content; } catch (IOException e) { throw new EbicsException(e.getMessage()); } } /** * Returns the content of a <code>ContentFactory</code> as a byte array * @param content * @return * @throws EbicsException */
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // Path: src/main/java/org/kopi/ebics/io/IOUtils.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; return file; } /** * Returns the content of a file as byte array. * @param path the file path * @return the byte array content of the file * @throws EbicsException */ public static byte[] getFileContent(String path) throws EbicsException { try { InputStream input; byte[] content; input = new FileInputStream(path); content = new byte[input.available()]; input.read(content); input.close(); return content; } catch (IOException e) { throw new EbicsException(e.getMessage()); } } /** * Returns the content of a <code>ContentFactory</code> as a byte array * @param content * @return * @throws EbicsException */
public static byte[] getFactoryContent(ContentFactory content) throws EbicsException {
pinaraf/ebics
src/main/java/org/kopi/ebics/interfaces/EbicsElement.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // }
import org.kopi.ebics.exception.EbicsException; import java.io.PrintStream; import java.io.Serializable;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.interfaces; public interface EbicsElement extends Serializable { /** * Returns the name of this <code>EbicsElement</code> * @return the name of the element */ public String getName(); /** * Builds the <code>EbicsElement</code> XML fragment * @throws EbicsException */
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // Path: src/main/java/org/kopi/ebics/interfaces/EbicsElement.java import org.kopi.ebics.exception.EbicsException; import java.io.PrintStream; import java.io.Serializable; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.interfaces; public interface EbicsElement extends Serializable { /** * Returns the name of this <code>EbicsElement</code> * @return the name of the element */ public String getName(); /** * Builds the <code>EbicsElement</code> XML fragment * @throws EbicsException */
public void build() throws EbicsException;
pinaraf/ebics
src/main/java/org/kopi/ebics/io/Splitter.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // }
import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.utils.Utils; import javax.crypto.spec.SecretKeySpec; import org.kopi.ebics.exception.EbicsException;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.io; /** * A mean to split a given input file to * 1MB portions. this i useful to handle * big file uploading. * * @author Hachani * */ public class Splitter { /** * Constructs a new <code>FileSplitter</code> with a given file. * @param input the input byte array */ public Splitter(byte[] input) { this.input = input; } /** * Reads the input stream and splits it to segments of 1MB size. * * <p>EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>The following procedure is to be followed with segmentation: * <ol> * <li> The order data is ZIP compressed * <li> The compressed order data is encrypted in accordance with Chapter 6.2 * <li> The compressed, encrypted order data is base64-coded. * <li> The result is to be verified with regard to the data volume: * <ol> * <li> If the resulting data volume is below the threshold of 1 MB = 1,048,576 bytes, * the order data can be sent complete as a data segment within one transmission step * <li> If the resulting data volume exceeds 1,048,576 bytes the data is to be * separated sequentially and in a base64-conformant manner into segments * that each have a maximum of 1,048,576 bytes. * </ol> * * @param isCompressionEnabled enable compression? * @param keySpec the secret key spec * @throws EbicsException */ public final void readInput(boolean isCompressionEnabled, SecretKeySpec keySpec)
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // Path: src/main/java/org/kopi/ebics/io/Splitter.java import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.utils.Utils; import javax.crypto.spec.SecretKeySpec; import org.kopi.ebics.exception.EbicsException; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.io; /** * A mean to split a given input file to * 1MB portions. this i useful to handle * big file uploading. * * @author Hachani * */ public class Splitter { /** * Constructs a new <code>FileSplitter</code> with a given file. * @param input the input byte array */ public Splitter(byte[] input) { this.input = input; } /** * Reads the input stream and splits it to segments of 1MB size. * * <p>EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>The following procedure is to be followed with segmentation: * <ol> * <li> The order data is ZIP compressed * <li> The compressed order data is encrypted in accordance with Chapter 6.2 * <li> The compressed, encrypted order data is base64-coded. * <li> The result is to be verified with regard to the data volume: * <ol> * <li> If the resulting data volume is below the threshold of 1 MB = 1,048,576 bytes, * the order data can be sent complete as a data segment within one transmission step * <li> If the resulting data volume exceeds 1,048,576 bytes the data is to be * separated sequentially and in a base64-conformant manner into segments * that each have a maximum of 1,048,576 bytes. * </ol> * * @param isCompressionEnabled enable compression? * @param keySpec the secret key spec * @throws EbicsException */ public final void readInput(boolean isCompressionEnabled, SecretKeySpec keySpec)
throws EbicsException
pinaraf/ebics
src/main/java/org/kopi/ebics/io/Splitter.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // }
import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.utils.Utils; import javax.crypto.spec.SecretKeySpec; import org.kopi.ebics.exception.EbicsException;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.io; /** * A mean to split a given input file to * 1MB portions. this i useful to handle * big file uploading. * * @author Hachani * */ public class Splitter { /** * Constructs a new <code>FileSplitter</code> with a given file. * @param input the input byte array */ public Splitter(byte[] input) { this.input = input; } /** * Reads the input stream and splits it to segments of 1MB size. * * <p>EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>The following procedure is to be followed with segmentation: * <ol> * <li> The order data is ZIP compressed * <li> The compressed order data is encrypted in accordance with Chapter 6.2 * <li> The compressed, encrypted order data is base64-coded. * <li> The result is to be verified with regard to the data volume: * <ol> * <li> If the resulting data volume is below the threshold of 1 MB = 1,048,576 bytes, * the order data can be sent complete as a data segment within one transmission step * <li> If the resulting data volume exceeds 1,048,576 bytes the data is to be * separated sequentially and in a base64-conformant manner into segments * that each have a maximum of 1,048,576 bytes. * </ol> * * @param isCompressionEnabled enable compression? * @param keySpec the secret key spec * @throws EbicsException */ public final void readInput(boolean isCompressionEnabled, SecretKeySpec keySpec) throws EbicsException { try { if (isCompressionEnabled) { input = Utils.zip(input); } content = Utils.encrypt(input, keySpec); segmentation(); } catch (Exception e) { throw new EbicsException(e.getMessage()); } } /** * Slits the input into 1MB portions. * * <p> EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>In Version H003 of the EBICS standard, order data that requires more than 1 MB of storage * space in compressed, encrypted and base64-coded form MUST be segmented before * transmission, irrespective of the transfer direction (upload/download). * */ private void segmentation() { numSegments = content.length / 1048576; //(1024 * 1024) if (content.length % 1048576 != 0) { numSegments ++; } segmentSize = content.length / numSegments; } /** * Returns the content of a data segment according to * a given segment number. * * @param segmentNumber the segment number * @return */
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // // Path: src/main/java/org/kopi/ebics/interfaces/ContentFactory.java // public interface ContentFactory extends Serializable { // // /** // * Returns a new data source of the data to be sent. // * The instance must ensure that the returned stream will // * deliver the identical data during the lifetime of this instance. // * Nevertheless how often the method will be called. // * @return a new data source of the data to be sent. // * @throws IOException // */ // public InputStream getContent() throws IOException; // } // Path: src/main/java/org/kopi/ebics/io/Splitter.java import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.utils.Utils; import javax.crypto.spec.SecretKeySpec; import org.kopi.ebics.exception.EbicsException; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.io; /** * A mean to split a given input file to * 1MB portions. this i useful to handle * big file uploading. * * @author Hachani * */ public class Splitter { /** * Constructs a new <code>FileSplitter</code> with a given file. * @param input the input byte array */ public Splitter(byte[] input) { this.input = input; } /** * Reads the input stream and splits it to segments of 1MB size. * * <p>EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>The following procedure is to be followed with segmentation: * <ol> * <li> The order data is ZIP compressed * <li> The compressed order data is encrypted in accordance with Chapter 6.2 * <li> The compressed, encrypted order data is base64-coded. * <li> The result is to be verified with regard to the data volume: * <ol> * <li> If the resulting data volume is below the threshold of 1 MB = 1,048,576 bytes, * the order data can be sent complete as a data segment within one transmission step * <li> If the resulting data volume exceeds 1,048,576 bytes the data is to be * separated sequentially and in a base64-conformant manner into segments * that each have a maximum of 1,048,576 bytes. * </ol> * * @param isCompressionEnabled enable compression? * @param keySpec the secret key spec * @throws EbicsException */ public final void readInput(boolean isCompressionEnabled, SecretKeySpec keySpec) throws EbicsException { try { if (isCompressionEnabled) { input = Utils.zip(input); } content = Utils.encrypt(input, keySpec); segmentation(); } catch (Exception e) { throw new EbicsException(e.getMessage()); } } /** * Slits the input into 1MB portions. * * <p> EBICS Specification 2.4.2 - 7 Segmentation of the order data: * * <p>In Version H003 of the EBICS standard, order data that requires more than 1 MB of storage * space in compressed, encrypted and base64-coded form MUST be segmented before * transmission, irrespective of the transfer direction (upload/download). * */ private void segmentation() { numSegments = content.length / 1048576; //(1024 * 1024) if (content.length % 1048576 != 0) { numSegments ++; } segmentSize = content.length / numSegments; } /** * Returns the content of a data segment according to * a given segment number. * * @param segmentNumber the segment number * @return */
public ContentFactory getContent(int segmentNumber) {
pinaraf/ebics
src/main/java/org/kopi/ebics/interfaces/LetterManager.java
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // }
import org.kopi.ebics.exception.EbicsException; import java.io.IOException; import java.security.GeneralSecurityException;
/* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.interfaces; /** * Initialization letters manager. * Manages the INI, HIA and the HPB letters. * * @author Hachani * */ public interface LetterManager { /** * Creates the initialization letter for the INI request. * This letter contains information about the signature certificate * of the given user. * @param user the ebics user. * @return the INI letter. * @throws EbicsException * @throws IOException * @throws GeneralSecurityException */ public InitLetter createA005Letter(EbicsUser user)
// Path: src/main/java/org/kopi/ebics/exception/EbicsException.java // public class EbicsException extends Exception { // // /** // * A means to construct a server error. // */ // public EbicsException() {} // // /** // * A means to construct a server error with an additional message. // * @param message the exception message // */ // public EbicsException(String message) { // super(message); // } // /** // * A means to construct a server error with no additional message. // * @param returnCode the ebics return code. // */ // public EbicsException(ReturnCode returnCode) { // this.returnCode = returnCode; // } // // /** // * A means to construct a server error with an additional message. // * @param returnCode the ebics return code. // * @param message the additional message. // */ // public EbicsException(ReturnCode returnCode, String message) { // super(message); // this.returnCode = returnCode; // } // // /** // * Returns the standardized error code. // * @return the standardized error code. // */ // public ReturnCode getReturnCode() { // return returnCode; // } // // // -------------------------------------------------------------------- // // DATA MEMBERS // // -------------------------------------------------------------------- // // private ReturnCode returnCode; // private static final long serialVersionUID = 2728820344946361669L; // } // Path: src/main/java/org/kopi/ebics/interfaces/LetterManager.java import org.kopi.ebics.exception.EbicsException; import java.io.IOException; import java.security.GeneralSecurityException; /* * Copyright (c) 1990-2012 kopiLeft Development SARL, Bizerte, Tunisia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.kopi.ebics.interfaces; /** * Initialization letters manager. * Manages the INI, HIA and the HPB letters. * * @author Hachani * */ public interface LetterManager { /** * Creates the initialization letter for the INI request. * This letter contains information about the signature certificate * of the given user. * @param user the ebics user. * @return the INI letter. * @throws EbicsException * @throws IOException * @throws GeneralSecurityException */ public InitLetter createA005Letter(EbicsUser user)
throws GeneralSecurityException, IOException, EbicsException;
channelaccess/ca
src/main/java/org/epics/ca/Channel.java
// Path: src/main/java/org/epics/ca/data/Metadata.java // public class Metadata<T> extends Data<T> // { // }
import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.epics.ca.data.Metadata;
package org.epics.ca; public interface Channel<T> extends AutoCloseable { String getName(); ConnectionState getConnectionState(); AccessRights getAccessRights(); Channel<T> connect(); CompletableFuture<Channel<T>> connectAsync(); // // listeners // Listener addConnectionListener( BiConsumer<Channel<T>, Boolean> handler ); Listener addAccessRightListener( BiConsumer<Channel<T>, AccessRights> handler ); // // sync methods, exception is thrown on failure // // NOTE: reusable get methods // T get(T reuse); // CompletableFuture<T> getAsync(T reuse); // <MT extends Metadata<T>> MT get(Class<? extends Metadata> clazz, T reuse); // <MT extends Metadata<T>> CompletableFuture<MT> getAsync(Class<? extends MT> clazz, T reuse); T get(); void put( T value ); void putNoWait( T value ); // best-effort put // // async methods, exception is reported via CompletableFuture // CompletableFuture<T> getAsync(); CompletableFuture<Status> putAsync( T value ); // NOTE: "public <MT extends Metadata<T>> MT get(Class<MT> clazz)" would // be a better definition, however it raises unchecked warnings in the code // and requires explicit casts for monitor APIs // the drawback of the signature below is that type of "?" can be different than "MT" // (it will raise ClassCastException if not properly used) @SuppressWarnings( "rawtypes" )
// Path: src/main/java/org/epics/ca/data/Metadata.java // public class Metadata<T> extends Data<T> // { // } // Path: src/main/java/org/epics/ca/Channel.java import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.epics.ca.data.Metadata; package org.epics.ca; public interface Channel<T> extends AutoCloseable { String getName(); ConnectionState getConnectionState(); AccessRights getAccessRights(); Channel<T> connect(); CompletableFuture<Channel<T>> connectAsync(); // // listeners // Listener addConnectionListener( BiConsumer<Channel<T>, Boolean> handler ); Listener addAccessRightListener( BiConsumer<Channel<T>, AccessRights> handler ); // // sync methods, exception is thrown on failure // // NOTE: reusable get methods // T get(T reuse); // CompletableFuture<T> getAsync(T reuse); // <MT extends Metadata<T>> MT get(Class<? extends Metadata> clazz, T reuse); // <MT extends Metadata<T>> CompletableFuture<MT> getAsync(Class<? extends MT> clazz, T reuse); T get(); void put( T value ); void putNoWait( T value ); // best-effort put // // async methods, exception is reported via CompletableFuture // CompletableFuture<T> getAsync(); CompletableFuture<Status> putAsync( T value ); // NOTE: "public <MT extends Metadata<T>> MT get(Class<MT> clazz)" would // be a better definition, however it raises unchecked warnings in the code // and requires explicit casts for monitor APIs // the drawback of the signature below is that type of "?" can be different than "MT" // (it will raise ClassCastException if not properly used) @SuppressWarnings( "rawtypes" )
<MT extends Metadata<T>> MT get( Class<? extends Metadata> clazz );
channelaccess/ca
src/test/java/org/epics/ca/impl/repeater/UdpSocketReceiver.java
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import net.jcip.annotations.ThreadSafe; import org.epics.ca.util.logging.LibraryLogManager; import java.io.IOException; import java.net.*; import java.util.logging.Logger;
/*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.repeater; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Test helper class which listens on a UDP socket and returns received * datagram packets */ @ThreadSafe class UdpSocketReceiver implements AutoCloseable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/test/java/org/epics/ca/impl/repeater/UdpSocketReceiver.java import net.jcip.annotations.ThreadSafe; import org.epics.ca.util.logging.LibraryLogManager; import java.io.IOException; import java.net.*; import java.util.logging.Logger; /*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.repeater; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Test helper class which listens on a UDP socket and returns received * datagram packets */ @ThreadSafe class UdpSocketReceiver implements AutoCloseable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/
private static final Logger logger = LibraryLogManager.getLogger( UdpSocketReceiver.class );
channelaccess/ca
src/main/java/org/epics/ca/util/PrintLibraryVersion.java
// Path: src/main/java/org/epics/ca/LibraryVersion.java // public final class LibraryVersion // { // // /** // * Returns a best-efforts string representation of the CA library that is // * running inside the current JVM by extracting information from the // * manifest file, if any, associated with the top level CA package. // * // * @return the version string or &lt;unknown&gt; if unavailable. // */ // public static String getAsString() // { // final String unknownVersion = "<unknown>"; // final Optional<Package> optPackage = Optional.ofNullable( LibraryVersion.class.getPackage() ); // // if ( optPackage.isPresent() ) // { // final Optional<String> optPackageImplementationVersion = Optional.ofNullable( optPackage.get().getImplementationVersion() ); // final Optional<String> optPackageSpecificationVersion = Optional.ofNullable( optPackage.get().getSpecificationVersion() ); // // if ( optPackageImplementationVersion.isPresent() ) // { // return optPackageImplementationVersion.get(); // } // // if ( optPackageSpecificationVersion.isPresent() ) // { // return optPackageSpecificationVersion.get(); // } // } // // return unknownVersion; // } // // }
import org.epics.ca.LibraryVersion;
package org.epics.ca.util; public class PrintLibraryVersion { public static void main( String[] args ) {
// Path: src/main/java/org/epics/ca/LibraryVersion.java // public final class LibraryVersion // { // // /** // * Returns a best-efforts string representation of the CA library that is // * running inside the current JVM by extracting information from the // * manifest file, if any, associated with the top level CA package. // * // * @return the version string or &lt;unknown&gt; if unavailable. // */ // public static String getAsString() // { // final String unknownVersion = "<unknown>"; // final Optional<Package> optPackage = Optional.ofNullable( LibraryVersion.class.getPackage() ); // // if ( optPackage.isPresent() ) // { // final Optional<String> optPackageImplementationVersion = Optional.ofNullable( optPackage.get().getImplementationVersion() ); // final Optional<String> optPackageSpecificationVersion = Optional.ofNullable( optPackage.get().getSpecificationVersion() ); // // if ( optPackageImplementationVersion.isPresent() ) // { // return optPackageImplementationVersion.get(); // } // // if ( optPackageSpecificationVersion.isPresent() ) // { // return optPackageSpecificationVersion.get(); // } // } // // return unknownVersion; // } // // } // Path: src/main/java/org/epics/ca/util/PrintLibraryVersion.java import org.epics.ca.LibraryVersion; package org.epics.ca.util; public class PrintLibraryVersion { public static void main( String[] args ) {
System.out.println( "Java CA v" + LibraryVersion.getAsString() );
channelaccess/ca
src/main/java/org/epics/ca/impl/monitor/blockingqueue/MonitorNotificationTask.java
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import net.jcip.annotations.Immutable; import org.apache.commons.lang3.Validate; import org.epics.ca.util.logging.LibraryLogManager; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger;
/*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.monitor.blockingqueue; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Runnable for transferring a monitor notification from a supplier to a consumer. * * @param <T> the type of the object to transfer. May sometimes refer to * monitor metadata or simply the most recent monitor value. */ @Immutable class MonitorNotificationTask<T> implements Runnable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/ // Get Logger
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/main/java/org/epics/ca/impl/monitor/blockingqueue/MonitorNotificationTask.java import net.jcip.annotations.Immutable; import org.apache.commons.lang3.Validate; import org.epics.ca.util.logging.LibraryLogManager; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; /*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.monitor.blockingqueue; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Runnable for transferring a monitor notification from a supplier to a consumer. * * @param <T> the type of the object to transfer. May sometimes refer to * monitor metadata or simply the most recent monitor value. */ @Immutable class MonitorNotificationTask<T> implements Runnable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/ // Get Logger
private static final Logger logger = LibraryLogManager.getLogger( MonitorNotificationTask.class );
channelaccess/ca
src/main/java/org/epics/ca/util/net/InetAddressUtil.java
// Path: src/main/java/org/epics/ca/Constants.java // public class Constants // { // // /*- Public attributes --------------------------------------------------------*/ // // public enum ChannelProperties // { // nativeType, nativeTypeCode, remoteAddress, nativeElementCount // } // // /** // * String value of the JVM property key which specifies whether to strip the hostname returned by // * InetAddress.getLocalHost().getHostName(). // */ // public static final String CA_STRIP_HOSTNAME = "CA_STRIP_HOSTNAME"; // // /** // * String value of the JVM property key to provide (override) hostname. // */ // public static final String CA_HOSTNAME_KEY = "HOSTNAME"; // // /** // * Minimal priority. // */ // public static final short CHANNEL_PRIORITY_MIN = 0; // // /** // * Maximal priority. // */ // public static final short CHANNEL_PRIORITY_MAX = 99; // // /** // * Default priority. // */ // public static final short CHANNEL_PRIORITY_DEFAULT = CHANNEL_PRIORITY_MIN; // // /** // * DB links priority. // */ // public static final short CHANNEL_PRIORITY_LINKS_DB = CHANNEL_PRIORITY_MAX; // // /** // * Archive priority. // */ // public static final short CHANNEL_PRIORITY_ARCHIVE = (short) ((CHANNEL_PRIORITY_MAX + CHANNEL_PRIORITY_MIN) / 2); // // /** // * OPI priority. // */ // public static final short CHANNEL_PRIORITY_OPI = CHANNEL_PRIORITY_MIN; // // /* -------- Core CA constants -------- */ // // /** // * CA protocol major revision (implemented by this library). // */ // public static final short CA_MAJOR_PROTOCOL_REVISION = 4; // // /** // * CA protocol minor revision (implemented by this library). // */ // public static final short CA_MINOR_PROTOCOL_REVISION = 13; // // /** // * Unknown CA protocol minor revision. // */ // public static final short CA_UNKNOWN_MINOR_PROTOCOL_REVISION = 0; // // /** // * Initial delay in milliseconds between creation of a new Context and the // * first attempt to register with the CA Repeater. // */ // public static final int CA_REPEATER_INITIAL_REGISTRATION_DELAY = 500; // // /** // * CA Repeater attempted registration interval in milliseconds. // */ // public static final int CA_REPEATER_REGISTRATION_INTERVAL = 60_000; // // /** // * CA protocol message header size. // */ // public static final short CA_MESSAGE_HEADER_SIZE = 16; // // /** // * CA protocol message extended header size. // */ // public static final short CA_EXTENDED_MESSAGE_HEADER_SIZE = (short) (CA_MESSAGE_HEADER_SIZE + 8); // // /** // * UDP maximum send message size. // * MAX_UDP: 1500 (max of Ethernet and 802.{2,3} MTU) - 20(IP) - 8(UDP) // * (the MTU of Ethernet is currently independent of its speed variant) // */ // public static final int MAX_UDP_SEND = 1024; // // /** // * UDP maximum receive message size. // */ // public static final int MAX_UDP_RECV = 0xFFFF + 16; // // /** // * TCP maximum receive message size. // */ // public static final int MAX_TCP_RECV = 1024 * 16 + CA_EXTENDED_MESSAGE_HEADER_SIZE; // // /** // * Default priority (corresponds to POSIX SCHED_OTHER) // */ // public static final short CA_DEFAULT_PRIORITY = 0; // // /** // * Read access right mask. // */ // public static final int CA_PROTO_ACCESS_RIGHT_READ = 1; // // /** // * Write access right mask. // */ // public static final int CA_PROTO_ACCESS_RIGHT_WRITE = 1 << 1; // // /** // * Do not require response for CA search request. // */ // public static final short CA_SEARCH_DONTREPLY = 5; // // /** // * Require response (even if not found) for CA search request over TCP. // */ // public static final short CA_SEARCH_DOREPLY = 10; // // /** // * Echo (state-of-health message) response timeout in ms. // */ // public static final long CA_ECHO_TIMEOUT = 5000; // // /** // * Max. (requested) string size. // */ // public static final int MAX_STRING_SIZE = 40; // // /** // * Unreasonable channel name length. // */ // public static final int UNREASONABLE_CHANNEL_NAME_LENGTH = 500; // // /*- Private attributes -------------------------------------------------------*/ // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // /*- Private methods ----------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import org.epics.ca.Constants;
// copy to array int appendSize = (appendList == null) ? 0 : appendList.length; InetSocketAddress[] isar = new InetSocketAddress[ al.size () + appendSize ]; al.toArray (isar); if ( appendSize > 0 ) { System.arraycopy(appendList, 0, isar, al.size(), appendSize); } return isar; } private static String hostName = null; public static synchronized String getHostName() { if ( hostName == null ) { // default fallback hostName = "localhost"; try { InetAddress localAddress = InetAddress.getLocalHost (); hostName = localAddress.getHostName (); } catch ( Throwable uhe ) { // not only UnknownHostException // try with environment variable try {
// Path: src/main/java/org/epics/ca/Constants.java // public class Constants // { // // /*- Public attributes --------------------------------------------------------*/ // // public enum ChannelProperties // { // nativeType, nativeTypeCode, remoteAddress, nativeElementCount // } // // /** // * String value of the JVM property key which specifies whether to strip the hostname returned by // * InetAddress.getLocalHost().getHostName(). // */ // public static final String CA_STRIP_HOSTNAME = "CA_STRIP_HOSTNAME"; // // /** // * String value of the JVM property key to provide (override) hostname. // */ // public static final String CA_HOSTNAME_KEY = "HOSTNAME"; // // /** // * Minimal priority. // */ // public static final short CHANNEL_PRIORITY_MIN = 0; // // /** // * Maximal priority. // */ // public static final short CHANNEL_PRIORITY_MAX = 99; // // /** // * Default priority. // */ // public static final short CHANNEL_PRIORITY_DEFAULT = CHANNEL_PRIORITY_MIN; // // /** // * DB links priority. // */ // public static final short CHANNEL_PRIORITY_LINKS_DB = CHANNEL_PRIORITY_MAX; // // /** // * Archive priority. // */ // public static final short CHANNEL_PRIORITY_ARCHIVE = (short) ((CHANNEL_PRIORITY_MAX + CHANNEL_PRIORITY_MIN) / 2); // // /** // * OPI priority. // */ // public static final short CHANNEL_PRIORITY_OPI = CHANNEL_PRIORITY_MIN; // // /* -------- Core CA constants -------- */ // // /** // * CA protocol major revision (implemented by this library). // */ // public static final short CA_MAJOR_PROTOCOL_REVISION = 4; // // /** // * CA protocol minor revision (implemented by this library). // */ // public static final short CA_MINOR_PROTOCOL_REVISION = 13; // // /** // * Unknown CA protocol minor revision. // */ // public static final short CA_UNKNOWN_MINOR_PROTOCOL_REVISION = 0; // // /** // * Initial delay in milliseconds between creation of a new Context and the // * first attempt to register with the CA Repeater. // */ // public static final int CA_REPEATER_INITIAL_REGISTRATION_DELAY = 500; // // /** // * CA Repeater attempted registration interval in milliseconds. // */ // public static final int CA_REPEATER_REGISTRATION_INTERVAL = 60_000; // // /** // * CA protocol message header size. // */ // public static final short CA_MESSAGE_HEADER_SIZE = 16; // // /** // * CA protocol message extended header size. // */ // public static final short CA_EXTENDED_MESSAGE_HEADER_SIZE = (short) (CA_MESSAGE_HEADER_SIZE + 8); // // /** // * UDP maximum send message size. // * MAX_UDP: 1500 (max of Ethernet and 802.{2,3} MTU) - 20(IP) - 8(UDP) // * (the MTU of Ethernet is currently independent of its speed variant) // */ // public static final int MAX_UDP_SEND = 1024; // // /** // * UDP maximum receive message size. // */ // public static final int MAX_UDP_RECV = 0xFFFF + 16; // // /** // * TCP maximum receive message size. // */ // public static final int MAX_TCP_RECV = 1024 * 16 + CA_EXTENDED_MESSAGE_HEADER_SIZE; // // /** // * Default priority (corresponds to POSIX SCHED_OTHER) // */ // public static final short CA_DEFAULT_PRIORITY = 0; // // /** // * Read access right mask. // */ // public static final int CA_PROTO_ACCESS_RIGHT_READ = 1; // // /** // * Write access right mask. // */ // public static final int CA_PROTO_ACCESS_RIGHT_WRITE = 1 << 1; // // /** // * Do not require response for CA search request. // */ // public static final short CA_SEARCH_DONTREPLY = 5; // // /** // * Require response (even if not found) for CA search request over TCP. // */ // public static final short CA_SEARCH_DOREPLY = 10; // // /** // * Echo (state-of-health message) response timeout in ms. // */ // public static final long CA_ECHO_TIMEOUT = 5000; // // /** // * Max. (requested) string size. // */ // public static final int MAX_STRING_SIZE = 40; // // /** // * Unreasonable channel name length. // */ // public static final int UNREASONABLE_CHANNEL_NAME_LENGTH = 500; // // /*- Private attributes -------------------------------------------------------*/ // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // /*- Private methods ----------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/main/java/org/epics/ca/util/net/InetAddressUtil.java import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import org.epics.ca.Constants; // copy to array int appendSize = (appendList == null) ? 0 : appendList.length; InetSocketAddress[] isar = new InetSocketAddress[ al.size () + appendSize ]; al.toArray (isar); if ( appendSize > 0 ) { System.arraycopy(appendList, 0, isar, al.size(), appendSize); } return isar; } private static String hostName = null; public static synchronized String getHostName() { if ( hostName == null ) { // default fallback hostName = "localhost"; try { InetAddress localAddress = InetAddress.getLocalHost (); hostName = localAddress.getHostName (); } catch ( Throwable uhe ) { // not only UnknownHostException // try with environment variable try {
String envHN = System.getenv (Constants.CA_HOSTNAME_KEY);
channelaccess/ca
src/main/java/org/epics/ca/impl/reactor/lf/LeaderFollowersThreadPool.java
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import org.epics.ca.util.logging.LibraryLogManager; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger;
package org.epics.ca.impl.reactor.lf; /** * LF thread pool implementation. */ public class LeaderFollowersThreadPool {
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/main/java/org/epics/ca/impl/reactor/lf/LeaderFollowersThreadPool.java import org.epics.ca.util.logging.LibraryLogManager; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; package org.epics.ca.impl.reactor.lf; /** * LF thread pool implementation. */ public class LeaderFollowersThreadPool {
private static final Logger logger = LibraryLogManager.getLogger( LeaderFollowersThreadPool.class );
channelaccess/ca
src/main/java/org/epics/ca/impl/monitor/striped/StripedMonitorNotificationTask.java
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import eu.javaspecialists.tjsn.concurrency.stripedexecutor.StripedRunnable; import net.jcip.annotations.Immutable; import org.apache.commons.lang3.Validate; import org.epics.ca.util.logging.LibraryLogManager; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger;
/*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.monitor.striped; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Runnable for transferring a monitor notification to a consumer. * * @param <T> the type of the object to transfer. May sometimes refer to * monitor metadata or simply the most recent monitor value. */ @Immutable class StripedMonitorNotificationTask<T> implements StripedRunnable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/main/java/org/epics/ca/impl/monitor/striped/StripedMonitorNotificationTask.java import eu.javaspecialists.tjsn.concurrency.stripedexecutor.StripedRunnable; import net.jcip.annotations.Immutable; import org.apache.commons.lang3.Validate; import org.epics.ca.util.logging.LibraryLogManager; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; /*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl.monitor.striped; /*- Imported packages --------------------------------------------------------*/ /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Runnable for transferring a monitor notification to a consumer. * * @param <T> the type of the object to transfer. May sometimes refer to * monitor metadata or simply the most recent monitor value. */ @Immutable class StripedMonitorNotificationTask<T> implements StripedRunnable { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/
private static final Logger logger = LibraryLogManager.getLogger( StripedMonitorNotificationTask.class );
channelaccess/ca
src/main/java/org/epics/ca/impl/reactor/Reactor.java
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // }
import org.epics.ca.util.logging.LibraryLogManager; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.AbstractSelectableChannel; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger;
package org.epics.ca.impl.reactor; /** * Implementation of reactor pattern using <code>java.nio.channels.Selector</code>. */ public class Reactor { // Get Logger
// Path: src/main/java/org/epics/ca/util/logging/LibraryLogManager.java // public class LibraryLogManager // { // // /*- Public attributes --------------------------------------------------------*/ // /*- Private attributes -------------------------------------------------------*/ // // private static final StreamHandler flushingStandardOutputStreamHandler; // // static // { // // Could consider here setting the default locale for this instance of // // the Java Virtual Machine. But currently (2020-05-10) it is not // // considered that the library "owns" this decision. // // Locale.setDefault( Locale.ROOT ); // // Note: the definition below determines the format of all log messages // // emitted by the CA library. // System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %3$s %4$s %5$s %6$s %n" ); // // // Create a stream handler that is like the normal output stream handler except // // it will ensure that each message gets flushed to the console. Note: this may // // impose some performance penalty during testing if copious messages are // // being logged. During normal CA usage the library does not emit many // // messages so in the normal situation this limitation should not be important. // flushingStandardOutputStreamHandler = new StreamHandler( System.out, new SimpleFormatter() ) // { // @Override // public synchronized void publish( final LogRecord record ) // { // super.publish( record ); // flush(); // } // }; // // // The output handler will emit all messages that are sent to it. It is up // // to the individual loggers to determine what is appropriate for their // // particular operating contexts. // flushingStandardOutputStreamHandler.setLevel( Level.ALL ); // } // // // /*- Main ---------------------------------------------------------------------*/ // /*- Constructor --------------------------------------------------------------*/ // /*- Public methods -----------------------------------------------------------*/ // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the level defined // * by the CA_LIBRARY_LOG_LEVEL system property. // * // * When CA_LIBRARY_LOG_LEVEL is not defined all messages of Level.INFO and // * above will be logged. // * // * @param clazz the class that the log messages will be associated with. // * @return the configured logger. // * // * throws NullPointerException if clazz was null. // * throws IllegalArgumentException if the string token associated with // * CA_LIBRARY_LOG_LEVEL could not be interpreted as a valid log level. // */ // public static Logger getLogger( Class<?> clazz ) // { // Validate.notNull( clazz ); // return getLogger( clazz, LibraryConfiguration.getInstance().getLibraryLogLevel() ); // } // // /** // * Returns a logger for the specified class that will send messages to the // * standard output stream providing their log level exceeds the specified // * log level. // * // * @param clazz the class that the logger will be associated with // * when logging messages. // * // * @param logLevel Set the log level specifying which message levels // * will be sent to the standard output stream by this logger. Message levels // * lower than this value will be discarded. The value Level.OFF can be // * used to completely turn off logging. // * // * @return the configured logger. // */ // public static Logger getLogger( Class<?> clazz, Level logLevel ) // { // // Currently (2020-05-14) the simple name is used in the log. This // // is considerably shorter than the fully qualified class name. Other // // implementations are possible. For example the Spring framework // // takes the approach of shortening the package names in the FQN to // // a single character. Another approach would be to extract the name // // automatically from the calling stack. // final Logger logger = Logger.getLogger( clazz.getSimpleName() ); // logger.setUseParentHandlers( false ); // // if ( logger.getHandlers().length == 0 ) // { // logger.addHandler( flushingStandardOutputStreamHandler ); // } // else // { // System.out.println( "\nWARNING: More than one logger defined for class: '" + clazz.getSimpleName() + "'.\n" ); // } // logger.setLevel( logLevel ); // // return logger; // } // // // /*- Package-level methods ----------------------------------------------------*/ // // /** // * Provided to enable tests only. // * @param logger the logger whose handlers are to be disposed. // */ // static void disposeLogger( Logger logger) // { // if ( logger.getHandlers().length == 1 ) // { // logger.removeHandler( flushingStandardOutputStreamHandler ); // } // } // // /*- Private methods ----------------------------------------------------------*/ // /*- Nested Classes -----------------------------------------------------------*/ // // } // Path: src/main/java/org/epics/ca/impl/reactor/Reactor.java import org.epics.ca.util.logging.LibraryLogManager; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.AbstractSelectableChannel; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; package org.epics.ca.impl.reactor; /** * Implementation of reactor pattern using <code>java.nio.channels.Selector</code>. */ public class Reactor { // Get Logger
private static final Logger logger = LibraryLogManager.getLogger( Reactor.class );
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/Getters.java
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // }
import net.dv8tion.jda.bot.sharding.ShardManager; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.Emote; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.SelfUser; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.exceptions.ErrorResponseException; import net.dv8tion.jda.core.utils.cache.SnowflakeCacheView; import stream.flarebot.flarebot.util.Constants; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
public static long getActiveVoiceChannels() { return getShardManager().getGuildCache().stream() .filter(c -> c.getAudioManager().getConnectedChannel() != null) .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) .count(); } public static int getSongsQueued() { return flareBot().getMusicManager().getPlayers().stream() .mapToInt(p -> p.getPlaylist().size()) .sum(); } // Other public static List<JDA> getShards() { return flareBot().getShardManager().getShards(); } @Nonnull public static SelfUser getSelfUser() { return flareBot().getClient().getSelfUser(); } @Nonnull public static ShardManager getShardManager() { return flareBot().getShardManager(); } public static Guild getOfficialGuild() {
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // } // Path: src/main/java/stream/flarebot/flarebot/Getters.java import net.dv8tion.jda.bot.sharding.ShardManager; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.Emote; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.SelfUser; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.exceptions.ErrorResponseException; import net.dv8tion.jda.core.utils.cache.SnowflakeCacheView; import stream.flarebot.flarebot.util.Constants; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public static long getActiveVoiceChannels() { return getShardManager().getGuildCache().stream() .filter(c -> c.getAudioManager().getConnectedChannel() != null) .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) .count(); } public static int getSongsQueued() { return flareBot().getMusicManager().getPlayers().stream() .mapToInt(p -> p.getPlaylist().size()) .sum(); } // Other public static List<JDA> getShards() { return flareBot().getShardManager().getShards(); } @Nonnull public static SelfUser getSelfUser() { return flareBot().getClient().getSelfUser(); } @Nonnull public static ShardManager getShardManager() { return flareBot().getShardManager(); } public static Guild getOfficialGuild() {
return getGuildById(Constants.OFFICIAL_GUILD);
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/metrics/collectors/BotCollector.java
// Path: src/main/java/stream/flarebot/flarebot/Getters.java // public class Getters { // // private static FlareBot flareBot() { // return FlareBot.instance(); // } // // // getXCache // public static SnowflakeCacheView<Guild> getGuildCache() { // return getShardManager().getGuildCache(); // } // // public static SnowflakeCacheView<TextChannel> getTextChannelCache() { // return getShardManager().getTextChannelCache(); // } // // public static SnowflakeCacheView<VoiceChannel> getVoiceChannelCache() { // return getShardManager().getVoiceChannelCache(); // } // // public static SnowflakeCacheView<User> getUserCache() { // return getShardManager().getUserCache(); // } // // // getXById // @Nullable // public static TextChannel getChannelById(String id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static TextChannel getChannelById(long id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static Guild getGuildById(String id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Guild getGuildById(long id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Emote getEmoteById(long emoteId) { // return getShardManager().getEmoteById(emoteId); // } // // @Nullable // public static User getUserById(String id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static User getUserById(long id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static Role getRoleById(String id) { // return getShardManager().getRoleById(id); // } // // @Nullable // public static Role getRoleById(long id) { // return getShardManager().getRoleById(id); // } // // // @Nullable // public static User retrieveUserById(long id) { // try { // return flareBot().getClient().retrieveUserById(id).complete(); // } catch (ErrorResponseException e) { // return null; // } // } // // // Audio // public static long getConnectedVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null).count(); // } // // public static Set<VoiceChannel> getConnectedVoiceChannel() { // return getShardManager().getGuildCache().stream().filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> g.getAudioManager().getConnectedChannel()) // .collect(Collectors.toSet()); // } // // public static long getActiveVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) // .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) // .count(); // } // // public static int getSongsQueued() { // return flareBot().getMusicManager().getPlayers().stream() // .mapToInt(p -> p.getPlaylist().size()) // .sum(); // } // // // Other // public static List<JDA> getShards() { // return flareBot().getShardManager().getShards(); // } // // @Nonnull // public static SelfUser getSelfUser() { // return flareBot().getClient().getSelfUser(); // } // // @Nonnull // public static ShardManager getShardManager() { // return flareBot().getShardManager(); // } // // public static Guild getOfficialGuild() { // return getGuildById(Constants.OFFICIAL_GUILD); // } // }
import io.prometheus.client.Collector; import io.prometheus.client.GaugeMetricFamily; import stream.flarebot.flarebot.Getters; import stream.flarebot.flarebot.metrics.BotMetrics; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package stream.flarebot.flarebot.metrics.collectors; public class BotCollector extends Collector { private final BotMetrics botMetrics; public BotCollector(BotMetrics botMetrics) { this.botMetrics = botMetrics; } @Override public List<MetricFamilySamples> collect() { List<MetricFamilySamples> familySamples = new ArrayList<>(); GaugeMetricFamily jdaEntities = new GaugeMetricFamily("flarebot_jda_entities_total", "Amount of JDA entities", Collections.singletonList("entity")); familySamples.add(jdaEntities); GaugeMetricFamily playerInfo = new GaugeMetricFamily("flarebot_player_info", "Amount of players, playing players and songs queued", Collections.singletonList("amount")); familySamples.add(playerInfo); if (botMetrics.count()) { jdaEntities.addMetric(Collections.singletonList("guilds"), botMetrics.getGuildCount()); jdaEntities.addMetric(Collections.singletonList("users"), botMetrics.getUserCount()); jdaEntities.addMetric(Collections.singletonList("text_channels"), botMetrics.getTextChannelCount()); jdaEntities.addMetric(Collections.singletonList("voice_channels"), botMetrics.getVoiceChannelCount());
// Path: src/main/java/stream/flarebot/flarebot/Getters.java // public class Getters { // // private static FlareBot flareBot() { // return FlareBot.instance(); // } // // // getXCache // public static SnowflakeCacheView<Guild> getGuildCache() { // return getShardManager().getGuildCache(); // } // // public static SnowflakeCacheView<TextChannel> getTextChannelCache() { // return getShardManager().getTextChannelCache(); // } // // public static SnowflakeCacheView<VoiceChannel> getVoiceChannelCache() { // return getShardManager().getVoiceChannelCache(); // } // // public static SnowflakeCacheView<User> getUserCache() { // return getShardManager().getUserCache(); // } // // // getXById // @Nullable // public static TextChannel getChannelById(String id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static TextChannel getChannelById(long id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static Guild getGuildById(String id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Guild getGuildById(long id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Emote getEmoteById(long emoteId) { // return getShardManager().getEmoteById(emoteId); // } // // @Nullable // public static User getUserById(String id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static User getUserById(long id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static Role getRoleById(String id) { // return getShardManager().getRoleById(id); // } // // @Nullable // public static Role getRoleById(long id) { // return getShardManager().getRoleById(id); // } // // // @Nullable // public static User retrieveUserById(long id) { // try { // return flareBot().getClient().retrieveUserById(id).complete(); // } catch (ErrorResponseException e) { // return null; // } // } // // // Audio // public static long getConnectedVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null).count(); // } // // public static Set<VoiceChannel> getConnectedVoiceChannel() { // return getShardManager().getGuildCache().stream().filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> g.getAudioManager().getConnectedChannel()) // .collect(Collectors.toSet()); // } // // public static long getActiveVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) // .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) // .count(); // } // // public static int getSongsQueued() { // return flareBot().getMusicManager().getPlayers().stream() // .mapToInt(p -> p.getPlaylist().size()) // .sum(); // } // // // Other // public static List<JDA> getShards() { // return flareBot().getShardManager().getShards(); // } // // @Nonnull // public static SelfUser getSelfUser() { // return flareBot().getClient().getSelfUser(); // } // // @Nonnull // public static ShardManager getShardManager() { // return flareBot().getShardManager(); // } // // public static Guild getOfficialGuild() { // return getGuildById(Constants.OFFICIAL_GUILD); // } // } // Path: src/main/java/stream/flarebot/flarebot/metrics/collectors/BotCollector.java import io.prometheus.client.Collector; import io.prometheus.client.GaugeMetricFamily; import stream.flarebot.flarebot.Getters; import stream.flarebot.flarebot.metrics.BotMetrics; import java.util.ArrayList; import java.util.Collections; import java.util.List; package stream.flarebot.flarebot.metrics.collectors; public class BotCollector extends Collector { private final BotMetrics botMetrics; public BotCollector(BotMetrics botMetrics) { this.botMetrics = botMetrics; } @Override public List<MetricFamilySamples> collect() { List<MetricFamilySamples> familySamples = new ArrayList<>(); GaugeMetricFamily jdaEntities = new GaugeMetricFamily("flarebot_jda_entities_total", "Amount of JDA entities", Collections.singletonList("entity")); familySamples.add(jdaEntities); GaugeMetricFamily playerInfo = new GaugeMetricFamily("flarebot_player_info", "Amount of players, playing players and songs queued", Collections.singletonList("amount")); familySamples.add(playerInfo); if (botMetrics.count()) { jdaEntities.addMetric(Collections.singletonList("guilds"), botMetrics.getGuildCount()); jdaEntities.addMetric(Collections.singletonList("users"), botMetrics.getUserCount()); jdaEntities.addMetric(Collections.singletonList("text_channels"), botMetrics.getTextChannelCount()); jdaEntities.addMetric(Collections.singletonList("voice_channels"), botMetrics.getVoiceChannelCount());
playerInfo.addMetric(Collections.singletonList("connected_voice_channels"), Getters.getConnectedVoiceChannels());
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/util/votes/VoteGroup.java
// Path: src/main/java/stream/flarebot/flarebot/Getters.java // public class Getters { // // private static FlareBot flareBot() { // return FlareBot.instance(); // } // // // getXCache // public static SnowflakeCacheView<Guild> getGuildCache() { // return getShardManager().getGuildCache(); // } // // public static SnowflakeCacheView<TextChannel> getTextChannelCache() { // return getShardManager().getTextChannelCache(); // } // // public static SnowflakeCacheView<VoiceChannel> getVoiceChannelCache() { // return getShardManager().getVoiceChannelCache(); // } // // public static SnowflakeCacheView<User> getUserCache() { // return getShardManager().getUserCache(); // } // // // getXById // @Nullable // public static TextChannel getChannelById(String id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static TextChannel getChannelById(long id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static Guild getGuildById(String id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Guild getGuildById(long id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Emote getEmoteById(long emoteId) { // return getShardManager().getEmoteById(emoteId); // } // // @Nullable // public static User getUserById(String id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static User getUserById(long id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static Role getRoleById(String id) { // return getShardManager().getRoleById(id); // } // // @Nullable // public static Role getRoleById(long id) { // return getShardManager().getRoleById(id); // } // // // @Nullable // public static User retrieveUserById(long id) { // try { // return flareBot().getClient().retrieveUserById(id).complete(); // } catch (ErrorResponseException e) { // return null; // } // } // // // Audio // public static long getConnectedVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null).count(); // } // // public static Set<VoiceChannel> getConnectedVoiceChannel() { // return getShardManager().getGuildCache().stream().filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> g.getAudioManager().getConnectedChannel()) // .collect(Collectors.toSet()); // } // // public static long getActiveVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) // .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) // .count(); // } // // public static int getSongsQueued() { // return flareBot().getMusicManager().getPlayers().stream() // .mapToInt(p -> p.getPlaylist().size()) // .sum(); // } // // // Other // public static List<JDA> getShards() { // return flareBot().getShardManager().getShards(); // } // // @Nonnull // public static SelfUser getSelfUser() { // return flareBot().getClient().getSelfUser(); // } // // @Nonnull // public static ShardManager getShardManager() { // return flareBot().getShardManager(); // } // // public static Guild getOfficialGuild() { // return getGuildById(Constants.OFFICIAL_GUILD); // } // }
import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.User; import stream.flarebot.flarebot.Getters; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.UUID;
package stream.flarebot.flarebot.util.votes; public class VoteGroup { private int yesVotes = 0; private int noVotes = 0; private final Set<Long> users = new HashSet<>(); private Set<Long> allowedUsers = new HashSet<>(); private final String messageDesc; private Message voteMessage; private long messageId; private EmbedBuilder votesEmbed; private UUID id; public VoteGroup(String messageDesc, UUID id) { this.messageDesc = messageDesc; this.id = id; } public boolean addVote(Vote vote, User user) { if (allowedUsers != null && voteMessage != null && !allowedUsers.contains(user.getIdLong())) return false; if (!users.contains(user.getIdLong())) { if (vote == Vote.NO) noVotes++; else yesVotes++; if (allowedUsers.size() == totalVotes()) {
// Path: src/main/java/stream/flarebot/flarebot/Getters.java // public class Getters { // // private static FlareBot flareBot() { // return FlareBot.instance(); // } // // // getXCache // public static SnowflakeCacheView<Guild> getGuildCache() { // return getShardManager().getGuildCache(); // } // // public static SnowflakeCacheView<TextChannel> getTextChannelCache() { // return getShardManager().getTextChannelCache(); // } // // public static SnowflakeCacheView<VoiceChannel> getVoiceChannelCache() { // return getShardManager().getVoiceChannelCache(); // } // // public static SnowflakeCacheView<User> getUserCache() { // return getShardManager().getUserCache(); // } // // // getXById // @Nullable // public static TextChannel getChannelById(String id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static TextChannel getChannelById(long id) { // return getShardManager().getTextChannelById(id); // } // // @Nullable // public static Guild getGuildById(String id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Guild getGuildById(long id) { // return getShardManager().getGuildById(id); // } // // @Nullable // public static Emote getEmoteById(long emoteId) { // return getShardManager().getEmoteById(emoteId); // } // // @Nullable // public static User getUserById(String id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static User getUserById(long id) { // return getShardManager().getUserById(id); // } // // @Nullable // public static Role getRoleById(String id) { // return getShardManager().getRoleById(id); // } // // @Nullable // public static Role getRoleById(long id) { // return getShardManager().getRoleById(id); // } // // // @Nullable // public static User retrieveUserById(long id) { // try { // return flareBot().getClient().retrieveUserById(id).complete(); // } catch (ErrorResponseException e) { // return null; // } // } // // // Audio // public static long getConnectedVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null).count(); // } // // public static Set<VoiceChannel> getConnectedVoiceChannel() { // return getShardManager().getGuildCache().stream().filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> g.getAudioManager().getConnectedChannel()) // .collect(Collectors.toSet()); // } // // public static long getActiveVoiceChannels() { // return getShardManager().getGuildCache().stream() // .filter(c -> c.getAudioManager().getConnectedChannel() != null) // .map(g -> flareBot().getMusicManager().getPlayer(g.getId())) // .filter(p -> p != null && p.getPlayingTrack() != null && !p.getPaused()) // .count(); // } // // public static int getSongsQueued() { // return flareBot().getMusicManager().getPlayers().stream() // .mapToInt(p -> p.getPlaylist().size()) // .sum(); // } // // // Other // public static List<JDA> getShards() { // return flareBot().getShardManager().getShards(); // } // // @Nonnull // public static SelfUser getSelfUser() { // return flareBot().getClient().getSelfUser(); // } // // @Nonnull // public static ShardManager getShardManager() { // return flareBot().getShardManager(); // } // // public static Guild getOfficialGuild() { // return getGuildById(Constants.OFFICIAL_GUILD); // } // } // Path: src/main/java/stream/flarebot/flarebot/util/votes/VoteGroup.java import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.User; import stream.flarebot.flarebot.Getters; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.UUID; package stream.flarebot.flarebot.util.votes; public class VoteGroup { private int yesVotes = 0; private int noVotes = 0; private final Set<Long> users = new HashSet<>(); private Set<Long> allowedUsers = new HashSet<>(); private final String messageDesc; private Message voteMessage; private long messageId; private EmbedBuilder votesEmbed; private UUID id; public VoteGroup(String messageDesc, UUID id) { this.messageDesc = messageDesc; this.id = id; } public boolean addVote(Vote vote, User user) { if (allowedUsers != null && voteMessage != null && !allowedUsers.contains(user.getIdLong())) return false; if (!users.contains(user.getIdLong())) { if (vote == Vote.NO) noVotes++; else yesVotes++; if (allowedUsers.size() == totalVotes()) {
VoteUtil.finishNow(id, Getters.getGuildById(voteMessage.getId()));
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/analytics/AnalyticSender.java
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // }
import org.json.JSONObject; import stream.flarebot.flarebot.util.Constants;
package stream.flarebot.flarebot.analytics; public interface AnalyticSender { /** * This is the data which will be sent, it needs to be a JSONObject and have a "data" field with whatever should be * sent. * <p> * <b>Make sure there is a "data" field if sending to FlareBot's API</b> * * @return The JSONObject to be sent. */ JSONObject processData(); /** * This is how often the analytic data should be sent in milliseconds. It is usually a good idea for readability * purposes to sue {@link java.util.concurrent.TimeUnit} and toMillis on any constant. * * @return The frequency that the data should be sent in milliseconds. */ long dataDeliveryFrequency(); /** * The endpoint which should be to sent to, this needs to have a leading / (slash). * * @return Endpoint for the sender data to be sent to with a trailing slash. */ String endpoint(); /** * The API URL which we will send the analytic data to, this should not include the endpoint for the said analytic data. * By default this is the FlareBot API as defined in {@link Constants#getAPI()} with the endpoint "analytics". * * @return API URL which the data will be sent to (Without endpoint). */ default String apiUrl() {
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // } // Path: src/main/java/stream/flarebot/flarebot/analytics/AnalyticSender.java import org.json.JSONObject; import stream.flarebot.flarebot.util.Constants; package stream.flarebot.flarebot.analytics; public interface AnalyticSender { /** * This is the data which will be sent, it needs to be a JSONObject and have a "data" field with whatever should be * sent. * <p> * <b>Make sure there is a "data" field if sending to FlareBot's API</b> * * @return The JSONObject to be sent. */ JSONObject processData(); /** * This is how often the analytic data should be sent in milliseconds. It is usually a good idea for readability * purposes to sue {@link java.util.concurrent.TimeUnit} and toMillis on any constant. * * @return The frequency that the data should be sent in milliseconds. */ long dataDeliveryFrequency(); /** * The endpoint which should be to sent to, this needs to have a leading / (slash). * * @return Endpoint for the sender data to be sent to with a trailing slash. */ String endpoint(); /** * The API URL which we will send the analytic data to, this should not include the endpoint for the said analytic data. * By default this is the FlareBot API as defined in {@link Constants#getAPI()} with the endpoint "analytics". * * @return API URL which the data will be sent to (Without endpoint). */ default String apiUrl() {
return Constants.getAPI() + "/analytics";
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/api/ApiRoute.java
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // }
import stream.flarebot.flarebot.util.Constants; import static stream.flarebot.flarebot.api.Method.GET; import static stream.flarebot.flarebot.api.Method.PATCH; import static stream.flarebot.flarebot.api.Method.POST; import static stream.flarebot.flarebot.api.Method.PUT;
package stream.flarebot.flarebot.api; public enum ApiRoute { // Root route COMMANDS(POST, "/commands"), // Stats route UPDATE_DATA(POST, "/stats/data"), DISPATCH_COMMAND(POST, "/stats/command"), // Guild route UPDATE_PREFIX(PATCH, "/guild/prefix"), // Guild/options route GET_OPTIONS_AUTOMODD(GET, "/guild/options/automod"), GET_OPTIONS_LANGUAGE(GET, "/guild/options/language"), // Debug route TEST(POST, "/test"), ; private Method method; private String route; ApiRoute(Method method, String route) { this.method = method; this.route = route; } public Method getMethod() { return this.method; } public String getRoute() { return this.route; } public String getFullUrl() {
// Path: src/main/java/stream/flarebot/flarebot/util/Constants.java // public class Constants { // // public static final long OFFICIAL_GUILD = 226785954537406464L; // private static final String FLAREBOT_API = "https://api.flarebot.stream"; // private static final String FLAREBOT_API_DEV = "http://localhost:8880"; // public static final String INVITE_URL = "https://discord.gg/TTAUGvZ"; // public static final String INVITE_MARKDOWN = "[Support Server](" + INVITE_URL + ")"; // // public static final long DEVELOPER_ID = 226788297156853771L; // public static final long ADMINS_ID = 434438873565888542L; // public static final long CONTRIBUTOR_ID = 272324832279003136L; // // private static final String FLARE_TEST_BOT_CHANNEL = "242297848123621376"; // public static final char COMMAND_CHAR = '_'; // public static final String COMMAND_CHAR_STRING = String.valueOf(COMMAND_CHAR); // // @Deprecated // public static Guild getOfficialGuild() { // return Getters.getGuildById(OFFICIAL_GUILD); // } // // public static TextChannel getErrorLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("226786557862871040")); // } // // public static TextChannel getGuildLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("260401007685664768")); // } // // private static TextChannel getEGLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358950369642151937")); // } // // public static void logEG(String eg, Command command, Guild guild, User user) { // EmbedBuilder builder = new EmbedBuilder().setTitle("Found `" + eg + "`") // .addField("Guild", guild.getId() + " (`" + guild.getName() + "`) ", true) // .addField("User", user.getAsMention() + " (`" + user.getName() + "#" + user.getDiscriminator() + "`)", true) // .setTimestamp(LocalDateTime.now(Clock.systemUTC())); // if (command != null) builder.addField("Command", command.getCommand(), true); // Constants.getEGLogChannel().sendMessage(builder.build()).queue(); // } // // public static TextChannel getImportantLogChannel() { // return (FlareBot.instance().isTestBot() ? // Getters.getChannelById(Constants.FLARE_TEST_BOT_CHANNEL) : // Getters.getChannelById("358978253966278657")); // } // // public static String getAPI() { // return FlareBot.instance().isTestBot() ? FLAREBOT_API_DEV : FLAREBOT_API; // } // } // Path: src/main/java/stream/flarebot/flarebot/api/ApiRoute.java import stream.flarebot.flarebot.util.Constants; import static stream.flarebot.flarebot.api.Method.GET; import static stream.flarebot.flarebot.api.Method.PATCH; import static stream.flarebot.flarebot.api.Method.POST; import static stream.flarebot.flarebot.api.Method.PUT; package stream.flarebot.flarebot.api; public enum ApiRoute { // Root route COMMANDS(POST, "/commands"), // Stats route UPDATE_DATA(POST, "/stats/data"), DISPATCH_COMMAND(POST, "/stats/command"), // Guild route UPDATE_PREFIX(PATCH, "/guild/prefix"), // Guild/options route GET_OPTIONS_AUTOMODD(GET, "/guild/options/automod"), GET_OPTIONS_LANGUAGE(GET, "/guild/options/language"), // Debug route TEST(POST, "/test"), ; private Method method; private String route; ApiRoute(Method method, String route) { this.method = method; this.route = route; } public Method getMethod() { return this.method; } public String getRoute() { return this.route; } public String getFullUrl() {
return Constants.getAPI() + route;
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/util/currency/CurrencyApiRoutes.java
// Path: src/main/java/stream/flarebot/flarebot/util/objects/ApiRoute.java // public class ApiRoute { // // private String url; // private int params; // // public String getUrl() { // return url; // } // // public int getParams() { // return params; // } // // public ApiRoute(String url) { // int open = StringUtils.countMatches(url, "{"); // if (open != StringUtils.countMatches(url, "}")) { // throw new IllegalArgumentException("Number of { does not match number of }"); // } // // this.url = url.replaceAll("\\{.*?}", "%s"); // this.params = open; // } // // public String getCompiledUrl(String... params) { // if (this.params != params.length) { // throw new IllegalArgumentException(String.format("Number of params given (%d) does not match required amount (%d) !", params.length, this.params)); // } // return String.format(this.url, params); // } // }
import stream.flarebot.flarebot.util.objects.ApiRoute;
package stream.flarebot.flarebot.util.currency; public class CurrencyApiRoutes { public static class NormalApi { private static final String BASE_URL = "https://api.fixer.io";
// Path: src/main/java/stream/flarebot/flarebot/util/objects/ApiRoute.java // public class ApiRoute { // // private String url; // private int params; // // public String getUrl() { // return url; // } // // public int getParams() { // return params; // } // // public ApiRoute(String url) { // int open = StringUtils.countMatches(url, "{"); // if (open != StringUtils.countMatches(url, "}")) { // throw new IllegalArgumentException("Number of { does not match number of }"); // } // // this.url = url.replaceAll("\\{.*?}", "%s"); // this.params = open; // } // // public String getCompiledUrl(String... params) { // if (this.params != params.length) { // throw new IllegalArgumentException(String.format("Number of params given (%d) does not match required amount (%d) !", params.length, this.params)); // } // return String.format(this.url, params); // } // } // Path: src/main/java/stream/flarebot/flarebot/util/currency/CurrencyApiRoutes.java import stream.flarebot.flarebot.util.objects.ApiRoute; package stream.flarebot.flarebot.util.currency; public class CurrencyApiRoutes { public static class NormalApi { private static final String BASE_URL = "https://api.fixer.io";
public static final ApiRoute LATEST_ALL = new ApiRoute(BASE_URL + "/latest");
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/mod/Infraction.java
// Path: src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java // public enum ModAction { // // BAN(true, ModlogEvent.USER_BANNED), // SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), // FORCE_BAN(true, ModlogEvent.USER_BANNED), // TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), // UNBAN(false, ModlogEvent.USER_UNBANNED), // // KICK(true, ModlogEvent.USER_KICKED), // // TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), // MUTE(true, ModlogEvent.USER_MUTED), // UNMUTE(false, ModlogEvent.USER_UNMUTED), // // WARN(true, ModlogEvent.USER_WARNED); // // private boolean infraction; // private ModlogEvent event; // // ModAction(boolean infraction, ModlogEvent modlogEvent) { // this.infraction = infraction; // this.event = modlogEvent; // } // // public boolean isInfraction() { // return infraction; // } // // @Override // public String toString() { // return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); // } // // public String getLowercaseName() { // return toString().toLowerCase(); // } // // public ModlogEvent getEvent() { // return event; // } // }
import stream.flarebot.flarebot.annotations.DoNotUse; import stream.flarebot.flarebot.mod.modlog.ModAction;
package stream.flarebot.flarebot.mod; public class Infraction { private int caseId;
// Path: src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java // public enum ModAction { // // BAN(true, ModlogEvent.USER_BANNED), // SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), // FORCE_BAN(true, ModlogEvent.USER_BANNED), // TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), // UNBAN(false, ModlogEvent.USER_UNBANNED), // // KICK(true, ModlogEvent.USER_KICKED), // // TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), // MUTE(true, ModlogEvent.USER_MUTED), // UNMUTE(false, ModlogEvent.USER_UNMUTED), // // WARN(true, ModlogEvent.USER_WARNED); // // private boolean infraction; // private ModlogEvent event; // // ModAction(boolean infraction, ModlogEvent modlogEvent) { // this.infraction = infraction; // this.event = modlogEvent; // } // // public boolean isInfraction() { // return infraction; // } // // @Override // public String toString() { // return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); // } // // public String getLowercaseName() { // return toString().toLowerCase(); // } // // public ModlogEvent getEvent() { // return event; // } // } // Path: src/main/java/stream/flarebot/flarebot/mod/Infraction.java import stream.flarebot.flarebot.annotations.DoNotUse; import stream.flarebot.flarebot.mod.modlog.ModAction; package stream.flarebot.flarebot.mod; public class Infraction { private int caseId;
private ModAction action;
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/network/RequestUrl.java
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // }
import com.didikee.cnbetareader.utils.MD5; import java.text.SimpleDateFormat; import java.util.Locale;
package com.didikee.cnbetareader.network; /** * Created by didik * Created time 2017/2/7 * Description: */ public class RequestUrl { private static final int SECOND = 1000; private static final int MINUTE = 60 * SECOND; private static final int HOUR = 60 * MINUTE; private static final int DAY = 24 * HOUR; private static final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); /** * 获取 Sid 小于 endSid 文章列表 * @param endSid 文章Sid * @return 文章列表url */ public static String getArticleListUrl(final String endSid) { StringBuilder sb = new StringBuilder(); sb.append("app_key=10000"); sb.append("&end_sid=").append(endSid); sb.append("&format=json"); sb.append("&method=Article.Lists"); sb.append("&timestamp=").append(System.currentTimeMillis()); sb.append("&v=2.8.5");
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // } // Path: app/src/main/java/com/didikee/cnbetareader/network/RequestUrl.java import com.didikee.cnbetareader.utils.MD5; import java.text.SimpleDateFormat; import java.util.Locale; package com.didikee.cnbetareader.network; /** * Created by didik * Created time 2017/2/7 * Description: */ public class RequestUrl { private static final int SECOND = 1000; private static final int MINUTE = 60 * SECOND; private static final int HOUR = 60 * MINUTE; private static final int DAY = 24 * HOUR; private static final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); /** * 获取 Sid 小于 endSid 文章列表 * @param endSid 文章Sid * @return 文章列表url */ public static String getArticleListUrl(final String endSid) { StringBuilder sb = new StringBuilder(); sb.append("app_key=10000"); sb.append("&end_sid=").append(endSid); sb.append("&format=json"); sb.append("&method=Article.Lists"); sb.append("&timestamp=").append(System.currentTimeMillis()); sb.append("&v=2.8.5");
final String signed = MD5.md5(sb.toString() + "&mpuffgvbvbttn3Rc");
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/adapters/ArticleListAdapter.java
// Path: app/src/main/java/com/didikee/cnbetareader/ui/views/interf/OnCommentsButtonClickListener.java // public interface OnCommentsButtonClickListener { // void onCommentsBtnClick(String sid,int comments); // } // // Path: app/src/main/java/com/didikee/cnbetareader/ui/views/interf/OnItemClickListener.java // public interface OnItemClickListener<T> { // void onItemClick(View view,T t); // }
import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.bean.ArticleListBean; import com.didikee.cnbetareader.ui.views.interf.OnCommentsButtonClickListener; import com.didikee.cnbetareader.ui.views.interf.OnItemClickListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.didikee.cnbetareader.adapters; /** * Created by didik * Created time 2017/2/9 * Description: */ public class ArticleListAdapter extends RecyclerView.Adapter<ArticleListAdapter.ViewHolder> { private OnItemClickListener<String> itemClickListener;
// Path: app/src/main/java/com/didikee/cnbetareader/ui/views/interf/OnCommentsButtonClickListener.java // public interface OnCommentsButtonClickListener { // void onCommentsBtnClick(String sid,int comments); // } // // Path: app/src/main/java/com/didikee/cnbetareader/ui/views/interf/OnItemClickListener.java // public interface OnItemClickListener<T> { // void onItemClick(View view,T t); // } // Path: app/src/main/java/com/didikee/cnbetareader/adapters/ArticleListAdapter.java import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.bean.ArticleListBean; import com.didikee.cnbetareader.ui.views.interf.OnCommentsButtonClickListener; import com.didikee.cnbetareader.ui.views.interf.OnItemClickListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package com.didikee.cnbetareader.adapters; /** * Created by didik * Created time 2017/2/9 * Description: */ public class ArticleListAdapter extends RecyclerView.Adapter<ArticleListAdapter.ViewHolder> { private OnItemClickListener<String> itemClickListener;
private OnCommentsButtonClickListener onCommentsButtonClickListener;
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/test/MyImageGetter.java
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // }
import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Environment; import android.text.Html.ImageGetter; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.utils.MD5; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
package com.didikee.cnbetareader.test; public class MyImageGetter implements ImageGetter { private Context context; private TextView tv; public MyImageGetter(Context context, TextView tv) { this.context = context; this.tv = tv; } @Override public Drawable getDrawable(String source) {
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // } // Path: app/src/main/java/com/didikee/cnbetareader/test/MyImageGetter.java import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Environment; import android.text.Html.ImageGetter; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.utils.MD5; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; package com.didikee.cnbetareader.test; public class MyImageGetter implements ImageGetter { private Context context; private TextView tv; public MyImageGetter(Context context, TextView tv) { this.context = context; this.tv = tv; } @Override public Drawable getDrawable(String source) {
String imageName = MD5.md5(source);
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/network/services/NewsCommentsService.java
// Path: app/src/main/java/com/didikee/cnbetareader/bean/CommentBeanList.java // public class CommentBeanList { // // /** // * status : success // * result : [{"tid":"13936685","pid":"0","username":"","content":"世界首款吗?你把中国的孕橙APP放哪里啦?", // * "created_time":"2017-02-10 17:29:14","support":"1","against":"2"},{"tid":"13936691", // * "pid":"0","username":"","content":"中国已经无数款了好不?!","created_time":"2017-02-10 17:29:47", // * "support":"1","against":"3"},{"tid":"13936717","pid":"0","username":"", // * "content":"下面说的国内的app有临床吗?有第三方认证吗?\u201c2016年针对4000名女性进行的临床试验表明这款app // * 和避孕药一样有效。目前,德国医学监管部门人员Tuv Sud认可这一app为Class IIb等级的医用设备\u201d","created_time":"2017-02-10 // * 17:40:22","support":"5","against":"0"},{"tid":"13936735","pid":"0","username":"", // * "content":"关键还是要体温计准确,APP再怎么算也是根据体温。难道还能算出花来?","created_time":"2017-02-10 17:44:41", // * "support":"1","against":"0"},{"tid":"13936739","pid":"0","username":"", // * "content":"不是西柚App吗","created_time":"2017-02-10 17:45:34","support":"0","against":"0"}, // * {"tid":"13936743","pid":"0","username":"","content":"30天换30个男人,这个APP能鉴定出爸爸是谁吗", // * "created_time":"2017-02-10 17:46:20","support":"6","against":"0"},{"tid":"13936751", // * "pid":"0","username":"","content":"从此可以愉快地约x了吗","created_time":"2017-02-10 17:49:11", // * "support":"0","against":"0"},{"tid":"13936771","pid":"0","username":"","content":"小心使用 // * 一不小心要出人命的啊","created_time":"2017-02-10 17:53:06","support":"4","against":"0"}, // * {"tid":"13936783","pid":"0","username":"", // * "content":"处男才会用的方法。在不安全的日子XXOO的体验明显好过其他时间。戴套就行了。","created_time":"2017-02-10 17:54:34", // * "support":"0","against":"7"},{"tid":"13936821","pid":"0","username":"", // * "content":"结果还是中标了~~","created_time":"2017-02-10 18:13:30","support":"0","against":"0"}] // */ // // private String status; // private List<CommentBean> result; // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public List<CommentBean> getResult() { // return result; // } // // public void setResult(List<CommentBean> result) { // this.result = result; // } // // }
import com.didikee.cnbetareader.bean.CommentBeanList; import retrofit2.http.GET; import retrofit2.http.Url; import rx.Observable;
package com.didikee.cnbetareader.network.services; /** * Created by didik * Created time 2017/2/10 * Description: */ public interface NewsCommentsService { @GET
// Path: app/src/main/java/com/didikee/cnbetareader/bean/CommentBeanList.java // public class CommentBeanList { // // /** // * status : success // * result : [{"tid":"13936685","pid":"0","username":"","content":"世界首款吗?你把中国的孕橙APP放哪里啦?", // * "created_time":"2017-02-10 17:29:14","support":"1","against":"2"},{"tid":"13936691", // * "pid":"0","username":"","content":"中国已经无数款了好不?!","created_time":"2017-02-10 17:29:47", // * "support":"1","against":"3"},{"tid":"13936717","pid":"0","username":"", // * "content":"下面说的国内的app有临床吗?有第三方认证吗?\u201c2016年针对4000名女性进行的临床试验表明这款app // * 和避孕药一样有效。目前,德国医学监管部门人员Tuv Sud认可这一app为Class IIb等级的医用设备\u201d","created_time":"2017-02-10 // * 17:40:22","support":"5","against":"0"},{"tid":"13936735","pid":"0","username":"", // * "content":"关键还是要体温计准确,APP再怎么算也是根据体温。难道还能算出花来?","created_time":"2017-02-10 17:44:41", // * "support":"1","against":"0"},{"tid":"13936739","pid":"0","username":"", // * "content":"不是西柚App吗","created_time":"2017-02-10 17:45:34","support":"0","against":"0"}, // * {"tid":"13936743","pid":"0","username":"","content":"30天换30个男人,这个APP能鉴定出爸爸是谁吗", // * "created_time":"2017-02-10 17:46:20","support":"6","against":"0"},{"tid":"13936751", // * "pid":"0","username":"","content":"从此可以愉快地约x了吗","created_time":"2017-02-10 17:49:11", // * "support":"0","against":"0"},{"tid":"13936771","pid":"0","username":"","content":"小心使用 // * 一不小心要出人命的啊","created_time":"2017-02-10 17:53:06","support":"4","against":"0"}, // * {"tid":"13936783","pid":"0","username":"", // * "content":"处男才会用的方法。在不安全的日子XXOO的体验明显好过其他时间。戴套就行了。","created_time":"2017-02-10 17:54:34", // * "support":"0","against":"7"},{"tid":"13936821","pid":"0","username":"", // * "content":"结果还是中标了~~","created_time":"2017-02-10 18:13:30","support":"0","against":"0"}] // */ // // private String status; // private List<CommentBean> result; // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public List<CommentBean> getResult() { // return result; // } // // public void setResult(List<CommentBean> result) { // this.result = result; // } // // } // Path: app/src/main/java/com/didikee/cnbetareader/network/services/NewsCommentsService.java import com.didikee.cnbetareader.bean.CommentBeanList; import retrofit2.http.GET; import retrofit2.http.Url; import rx.Observable; package com.didikee.cnbetareader.network.services; /** * Created by didik * Created time 2017/2/10 * Description: */ public interface NewsCommentsService { @GET
Observable<CommentBeanList> getNewsComments(@Url String commentsUrl);
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/test/MyTagHandler.java
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.text.Editable; import android.text.Html.TagHandler; import android.text.Spanned; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.view.View; import com.didikee.cnbetareader.utils.MD5; import org.xml.sax.XMLReader; import java.io.File;
package com.didikee.cnbetareader.test; public class MyTagHandler implements TagHandler { private Context context; public MyTagHandler(Context context) { this.context = context; } @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { // TODO Auto-generated method stub // �����ǩ<img> if (tag.toLowerCase().equals("img")) { // ��ȡ���� int len = output.length(); // ��ȡͼƬ��ַ ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class); String imgURL = images[0].getSource(); // ʹͼƬ�ɵ������������¼� output.setSpan(new ImageClick(context, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } private class ImageClick extends ClickableSpan { private String url; private Context context; public ImageClick(Context context, String url) { this.context = context; this.url = url; } @Override public void onClick(View widget) { // TODO Auto-generated method stub // ��ͼƬURLת��Ϊ����·�������Խ�ͼƬ���������ͼƬ�������дΪһ���������������
// Path: app/src/main/java/com/didikee/cnbetareader/utils/MD5.java // public class MD5 { // public static String md5(String content){ // byte[] result; // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(content.getBytes("UTF-8")); // result = messageDigest.digest(); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return ""; // } // return byte2Hex(result); // } // private static String byte2Hex(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (byte b: bytes) { // String hex = Integer.toHexString(b & 0xFF); // if (hex.length() == 1) { // hex = "0" + hex; // one byte to double-digit hex // } // sb.append(hex); // } // return sb.toString(); // } // } // Path: app/src/main/java/com/didikee/cnbetareader/test/MyTagHandler.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.text.Editable; import android.text.Html.TagHandler; import android.text.Spanned; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.view.View; import com.didikee.cnbetareader.utils.MD5; import org.xml.sax.XMLReader; import java.io.File; package com.didikee.cnbetareader.test; public class MyTagHandler implements TagHandler { private Context context; public MyTagHandler(Context context) { this.context = context; } @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { // TODO Auto-generated method stub // �����ǩ<img> if (tag.toLowerCase().equals("img")) { // ��ȡ���� int len = output.length(); // ��ȡͼƬ��ַ ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class); String imgURL = images[0].getSource(); // ʹͼƬ�ɵ������������¼� output.setSpan(new ImageClick(context, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } private class ImageClick extends ClickableSpan { private String url; private Context context; public ImageClick(Context context, String url) { this.context = context; this.url = url; } @Override public void onClick(View widget) { // TODO Auto-generated method stub // ��ͼƬURLת��Ϊ����·�������Խ�ͼƬ���������ͼƬ�������дΪһ���������������
String imageName = MD5.md5(url);
didikee/cnBetaGeek
app/src/main/java/com/didikee/cnbetareader/adapters/CommentsAdapter.java
// Path: app/src/main/java/com/didikee/cnbetareader/bean/CommentBean.java // public class CommentBean { // /** // * tid : 13936685 // * pid : 0 // * username : // * content : 世界首款吗?你把中国的孕橙APP放哪里啦? // * created_time : 2017-02-10 17:29:14 // * support : 1 // * against : 2 // */ // // private String tid; // private String pid; // private String username; // private String content; // private String created_time; // private String support; // private String against; // // public String getTid() { // return tid; // } // // public void setTid(String tid) { // this.tid = tid; // } // // public String getPid() { // return pid; // } // // public void setPid(String pid) { // this.pid = pid; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getCreated_time() { // return created_time; // } // // public void setCreated_time(String created_time) { // this.created_time = created_time; // } // // public String getSupport() { // return support; // } // // public void setSupport(String support) { // this.support = support; // } // // public String getAgainst() { // return against; // } // // public void setAgainst(String against) { // this.against = against; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.bean.CommentBean; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.didikee.cnbetareader.adapters; /** * Created by didik * Created time 2017/2/10 * Description: */ public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> { // private List<ArrayList<CommentBean>> data; private Context context;
// Path: app/src/main/java/com/didikee/cnbetareader/bean/CommentBean.java // public class CommentBean { // /** // * tid : 13936685 // * pid : 0 // * username : // * content : 世界首款吗?你把中国的孕橙APP放哪里啦? // * created_time : 2017-02-10 17:29:14 // * support : 1 // * against : 2 // */ // // private String tid; // private String pid; // private String username; // private String content; // private String created_time; // private String support; // private String against; // // public String getTid() { // return tid; // } // // public void setTid(String tid) { // this.tid = tid; // } // // public String getPid() { // return pid; // } // // public void setPid(String pid) { // this.pid = pid; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getCreated_time() { // return created_time; // } // // public void setCreated_time(String created_time) { // this.created_time = created_time; // } // // public String getSupport() { // return support; // } // // public void setSupport(String support) { // this.support = support; // } // // public String getAgainst() { // return against; // } // // public void setAgainst(String against) { // this.against = against; // } // } // Path: app/src/main/java/com/didikee/cnbetareader/adapters/CommentsAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.didikee.cnbetareader.R; import com.didikee.cnbetareader.bean.CommentBean; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package com.didikee.cnbetareader.adapters; /** * Created by didik * Created time 2017/2/10 * Description: */ public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> { // private List<ArrayList<CommentBean>> data; private Context context;
private List<CommentBean> data = new ArrayList<>();
wso2/developer-studio
plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/utils/CSMediaUtils.java
// Path: plugins/org.wso2.developerstudio.eclipse.logging/src/org/wso2/developerstudio/eclipse/logging/core/IDeveloperStudioLog.java // public interface IDeveloperStudioLog { // // public void setPluginId(String pluginId); // // public String getPluginId(); // // public void setClassObj(Class<Object> classObj); // // public Class<Object> getClassObj(); // // public void info(String message); // // public void info(String message, Exception e); // // public void warn(String message); // // public void warn(String message, Exception e); // // public void error(String message); // // public void error(Exception e); // // public void error(String message, Exception e); // // public void error(Throwable e); // // public void error(String message, Throwable e); // // public void info(Throwable e); // // public void info(String message, Throwable e); // // public void warn(Throwable e); // // public void warn(String message, Throwable e); // // } // // Path: plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/Activator.java // public class Activator extends AbstractUIPlugin { // // public static final String PLUGIN_ID = "org.wso2.tools.eclipse.platform.core"; // // private static Activator plugin; // // public Activator() { // } // // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // public static Activator getDefault() { // return plugin; // } // // } // // Path: plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/interfaces/IMediaTypeResolver.java // public abstract interface IMediaTypeResolver { // // }
import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.platform.core.Activator; import org.wso2.developerstudio.eclipse.platform.core.interfaces.IMediaTypeResolver; import org.wso2.developerstudio.eclipse.platform.core.interfaces.IMediaTypeResolverProvider; import org.wso2.developerstudio.eclipse.platform.core.internal.impl.MediaTypeResolverProviderImpl;
/* * Copyright (c) 2010-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.developerstudio.eclipse.platform.core.utils; public class CSMediaUtils { private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID); private static String MEDIA_TYPE_EXTENSION = "org.wso2.developerstudio.eclipse.platform.core.mediatype"; private static List<IMediaTypeResolverProvider> mediaTypeResolverList; public static IMediaTypeResolverProvider[] getMediaTypeResolver() { return mediaTypeResolverList.toArray(new IMediaTypeResolverProvider[] {}); } static { mediaTypeResolverList = new ArrayList<IMediaTypeResolverProvider>(); IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor(MEDIA_TYPE_EXTENSION); for (IConfigurationElement e : config) { try { MediaTypeResolverProviderImpl providers = new MediaTypeResolverProviderImpl(); providers.setId(e.getAttribute("id")); providers.setMediaType(e.getAttribute("mediaType")); String extensions = e.getAttribute("extensions"); if (extensions != null && !extensions.trim().equals("")) { providers.addExtensions(extensions.split(",")); }
// Path: plugins/org.wso2.developerstudio.eclipse.logging/src/org/wso2/developerstudio/eclipse/logging/core/IDeveloperStudioLog.java // public interface IDeveloperStudioLog { // // public void setPluginId(String pluginId); // // public String getPluginId(); // // public void setClassObj(Class<Object> classObj); // // public Class<Object> getClassObj(); // // public void info(String message); // // public void info(String message, Exception e); // // public void warn(String message); // // public void warn(String message, Exception e); // // public void error(String message); // // public void error(Exception e); // // public void error(String message, Exception e); // // public void error(Throwable e); // // public void error(String message, Throwable e); // // public void info(Throwable e); // // public void info(String message, Throwable e); // // public void warn(Throwable e); // // public void warn(String message, Throwable e); // // } // // Path: plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/Activator.java // public class Activator extends AbstractUIPlugin { // // public static final String PLUGIN_ID = "org.wso2.tools.eclipse.platform.core"; // // private static Activator plugin; // // public Activator() { // } // // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // public static Activator getDefault() { // return plugin; // } // // } // // Path: plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/interfaces/IMediaTypeResolver.java // public abstract interface IMediaTypeResolver { // // } // Path: plugins/org.wso2.developerstudio.eclipse.platform.core/src/org/wso2/developerstudio/eclipse/platform/core/utils/CSMediaUtils.java import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.platform.core.Activator; import org.wso2.developerstudio.eclipse.platform.core.interfaces.IMediaTypeResolver; import org.wso2.developerstudio.eclipse.platform.core.interfaces.IMediaTypeResolverProvider; import org.wso2.developerstudio.eclipse.platform.core.internal.impl.MediaTypeResolverProviderImpl; /* * Copyright (c) 2010-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.developerstudio.eclipse.platform.core.utils; public class CSMediaUtils { private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID); private static String MEDIA_TYPE_EXTENSION = "org.wso2.developerstudio.eclipse.platform.core.mediatype"; private static List<IMediaTypeResolverProvider> mediaTypeResolverList; public static IMediaTypeResolverProvider[] getMediaTypeResolver() { return mediaTypeResolverList.toArray(new IMediaTypeResolverProvider[] {}); } static { mediaTypeResolverList = new ArrayList<IMediaTypeResolverProvider>(); IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor(MEDIA_TYPE_EXTENSION); for (IConfigurationElement e : config) { try { MediaTypeResolverProviderImpl providers = new MediaTypeResolverProviderImpl(); providers.setId(e.getAttribute("id")); providers.setMediaType(e.getAttribute("mediaType")); String extensions = e.getAttribute("extensions"); if (extensions != null && !extensions.trim().equals("")) { providers.addExtensions(extensions.split(",")); }
providers.setMediaTypeResolver((IMediaTypeResolver) e.createExecutableExtension("class"));
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEventManager.java // public interface GraphEventManager // { // // /** // * <p> // * This method is called by the framework. Custom skins should <b>not</b> // * call it. // * </p> // * // * @param pGesture // * {@link GraphInputGesture} to check // * @param pEvent // * {@link Event} // * @param pOwner // * owner // * @return {@code true} if the given gesture was activated otherwise // * {@code false} // */ // boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner); // // /** // * <p> // * This method is called by the framework. Custom skins should <b>not</b> // * call it. // * </p> // * // * @param pExpected // * the expected gesture that should be finished // * @param pOwner // * owner // * @return {@code true} if the state changed as a result of this operation // * or {@code false} // */ // boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphInputGesture.java // public enum GraphInputGesture // { // // /** // * Panning / moving the graph editor viewport // */ // PAN, // // /** // * Zooming the graph editor viewport // */ // ZOOM, // // /** // * Resizing graph editor elements // */ // RESIZE, // // /** // * Moving graph editor elements // */ // MOVE, // // /** // * Connecting graph editor elements // */ // CONNECT, // // /** // * Selecting graph editor elements // */ // SELECT; // }
import de.tesis.dynaware.grapheditor.utils.GraphEventManager; import de.tesis.dynaware.grapheditor.utils.GraphInputGesture; import javafx.event.Event; import javafx.scene.Node; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.TouchEvent; import javafx.scene.input.ZoomEvent;
package de.tesis.dynaware.grapheditor.impl; /** * Default implementation of {@link GraphEventManager} */ public class GraphEventManagerImpl implements GraphEventManager {
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEventManager.java // public interface GraphEventManager // { // // /** // * <p> // * This method is called by the framework. Custom skins should <b>not</b> // * call it. // * </p> // * // * @param pGesture // * {@link GraphInputGesture} to check // * @param pEvent // * {@link Event} // * @param pOwner // * owner // * @return {@code true} if the given gesture was activated otherwise // * {@code false} // */ // boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner); // // /** // * <p> // * This method is called by the framework. Custom skins should <b>not</b> // * call it. // * </p> // * // * @param pExpected // * the expected gesture that should be finished // * @param pOwner // * owner // * @return {@code true} if the state changed as a result of this operation // * or {@code false} // */ // boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphInputGesture.java // public enum GraphInputGesture // { // // /** // * Panning / moving the graph editor viewport // */ // PAN, // // /** // * Zooming the graph editor viewport // */ // ZOOM, // // /** // * Resizing graph editor elements // */ // RESIZE, // // /** // * Moving graph editor elements // */ // MOVE, // // /** // * Connecting graph editor elements // */ // CONNECT, // // /** // * Selecting graph editor elements // */ // SELECT; // } // Path: api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java import de.tesis.dynaware.grapheditor.utils.GraphEventManager; import de.tesis.dynaware.grapheditor.utils.GraphInputGesture; import javafx.event.Event; import javafx.scene.Node; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.TouchEvent; import javafx.scene.input.ZoomEvent; package de.tesis.dynaware.grapheditor.impl; /** * Default implementation of {@link GraphEventManager} */ public class GraphEventManagerImpl implements GraphEventManager {
private GraphInputGesture gesture;
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/utils/DraggableBox.java
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import de.tesis.dynaware.grapheditor.EditorElement; import javafx.event.Event; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * A draggable box that can display children. * * <p> * This is a subclass of {@link StackPane} and will lay out its children accordingly. The size of the box should be set * via {@code resize(width, height)}, and will not be affected by parent layout. * </p> */ public class DraggableBox extends StackPane { private static final double DEFAULT_ALIGNMENT_THRESHOLD = 5;
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/DraggableBox.java import de.tesis.dynaware.grapheditor.EditorElement; import javafx.event.Event; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; /* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * A draggable box that can display children. * * <p> * This is a subclass of {@link StackPane} and will lay out its children accordingly. The size of the box should be set * via {@code resize(width, height)}, and will not be affected by parent layout. * </p> */ public class DraggableBox extends StackPane { private static final double DEFAULT_ALIGNMENT_THRESHOLD = 5;
private final EditorElement mType;
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; public class DraggableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private static final double BOX_WIDTH = 80; private static final double BOX_HEIGHT = 50; private static final double BOX_INITIAL_X = 48; private static final double BOX_INITIAL_Y = 39; private static final double BOUNDARY_INDENT = 12; private static final double GRID_SPACING = 11; private static final double ALIGNMENT_THRESHOLD = 16;
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; /* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; public class DraggableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private static final double BOX_WIDTH = 80; private static final double BOX_HEIGHT = 50; private static final double BOX_INITIAL_X = 48; private static final double BOX_INITIAL_Y = 39; private static final double BOUNDARY_INDENT = 12; private static final double GRID_SPACING = 11; private static final double ALIGNMENT_THRESHOLD = 16;
private final DraggableBox box = new DraggableBox(EditorElement.NODE);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
private final DraggableBox box = new DraggableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { properties.setEastBoundValue(BOUNDARY_INDENT); properties.setWestBoundValue(BOUNDARY_INDENT); properties.setNorthBoundValue(BOUNDARY_INDENT); properties.setSouthBoundValue(BOUNDARY_INDENT); properties.setSnapToGrid(false); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); box.setAlignmentTargetsX(null); box.setAlignmentTargetsY(null); box.setEditorProperties(properties); container.setPrefSize(400, 300); container.autosize(); container.getChildren().add(box); } @Test public void testDrag_Simple() { // Try some simple drag operations.
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; private final DraggableBox box = new DraggableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { properties.setEastBoundValue(BOUNDARY_INDENT); properties.setWestBoundValue(BOUNDARY_INDENT); properties.setNorthBoundValue(BOUNDARY_INDENT); properties.setSouthBoundValue(BOUNDARY_INDENT); properties.setSnapToGrid(false); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); box.setAlignmentTargetsX(null); box.setAlignmentTargetsY(null); box.setEditorProperties(properties); container.setPrefSize(400, 300); container.autosize(); container.getChildren().add(box); } @Test public void testDrag_Simple() { // Try some simple drag operations.
dragBy(box, 100, 100);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
properties.setEastBoundValue(BOUNDARY_INDENT); properties.setWestBoundValue(BOUNDARY_INDENT); properties.setNorthBoundValue(BOUNDARY_INDENT); properties.setSouthBoundValue(BOUNDARY_INDENT); properties.setSnapToGrid(false); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); box.setAlignmentTargetsX(null); box.setAlignmentTargetsY(null); box.setEditorProperties(properties); container.setPrefSize(400, 300); container.autosize(); container.getChildren().add(box); } @Test public void testDrag_Simple() { // Try some simple drag operations. dragBy(box, 100, 100); assertAt(BOX_INITIAL_X + 100, BOX_INITIAL_Y + 100); dragBy(box, -50, 75); assertAt(BOX_INITIAL_X + 50, BOX_INITIAL_Y + 175); // Move the cursor to the top left of the scene - should stop at the boundary values.
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; properties.setEastBoundValue(BOUNDARY_INDENT); properties.setWestBoundValue(BOUNDARY_INDENT); properties.setNorthBoundValue(BOUNDARY_INDENT); properties.setSouthBoundValue(BOUNDARY_INDENT); properties.setSnapToGrid(false); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); box.setAlignmentTargetsX(null); box.setAlignmentTargetsY(null); box.setEditorProperties(properties); container.setPrefSize(400, 300); container.autosize(); container.getChildren().add(box); } @Test public void testDrag_Simple() { // Try some simple drag operations. dragBy(box, 100, 100); assertAt(BOX_INITIAL_X + 100, BOX_INITIAL_Y + 100); dragBy(box, -50, 75); assertAt(BOX_INITIAL_X + 50, BOX_INITIAL_Y + 175); // Move the cursor to the top left of the scene - should stop at the boundary values.
dragTo(box, 10, 10);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
final double y = box.getLayoutY(); assertTrue(x == Math.round(x / GRID_SPACING) * GRID_SPACING); assertTrue(y == Math.round(y / GRID_SPACING) * GRID_SPACING); } @Test public void testDrag_AlignmentTargets() { final double[] alignmentTargetsX = new double[] {67.0}; final double[] alignmentTargetsY = new double[] {184.0}; box.setAlignmentThreshold(ALIGNMENT_THRESHOLD); box.setAlignmentTargetsX(alignmentTargetsX); box.setAlignmentTargetsY(alignmentTargetsY); dragTo(box, 40 + BOX_WIDTH / 2, 0); assertTrue(box.getLayoutX() == 67.0); dragTo(box, 0, 170 + BOX_HEIGHT / 2); assertTrue(box.getLayoutY() == 184.0); } /** * Asserts that the box's layout X and Y values are at the given positions. * * @param x the x value that the box should have * @param y the y value that the box should have */ private void assertAt(final double x, final double y) {
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragTo(final Node node, final double endX, final double endY) { // dragTo(node, 0, 0, endX, endY); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/DraggableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragTo; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; final double y = box.getLayoutY(); assertTrue(x == Math.round(x / GRID_SPACING) * GRID_SPACING); assertTrue(y == Math.round(y / GRID_SPACING) * GRID_SPACING); } @Test public void testDrag_AlignmentTargets() { final double[] alignmentTargetsX = new double[] {67.0}; final double[] alignmentTargetsY = new double[] {184.0}; box.setAlignmentThreshold(ALIGNMENT_THRESHOLD); box.setAlignmentTargetsX(alignmentTargetsX); box.setAlignmentTargetsY(alignmentTargetsY); dragTo(box, 40 + BOX_WIDTH / 2, 0); assertTrue(box.getLayoutX() == 67.0); dragTo(box, 0, 170 + BOX_HEIGHT / 2); assertTrue(box.getLayoutY() == 184.0); } /** * Asserts that the box's layout X and Y values are at the given positions. * * @param x the x value that the box should have * @param y the y value that the box should have */ private void assertAt(final double x, final double y) {
forceLayoutUpdate(container);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1;
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1;
private final ResizableBox box = new ResizableBox(EditorElement.NODE);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1; private final ResizableBox box = new ResizableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { box.setEditorProperties(properties); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); container.setPrefSize(360, 300); container.autosize(); container.getChildren().add(box);
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1; private final ResizableBox box = new ResizableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { box.setEditorProperties(properties); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); container.setPrefSize(360, 300); container.autosize(); container.getChildren().add(box);
forceLayoutUpdate(container);
eckig/graph-editor
api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane;
package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1; private final ResizableBox box = new ResizableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { box.setEditorProperties(properties); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); container.setPrefSize(360, 300); container.autosize(); container.getChildren().add(box); forceLayoutUpdate(container); } @Test public void testResize_UpperLeftCorner() {
// Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void dragBy(final Node node, final double dx, final double dy) { // dragTo(node, node.getLayoutX() + dx, node.getLayoutY() + dy); // } // // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/FXTestUtils.java // public static void forceLayoutUpdate(final Parent parent) { // parent.autosize(); // parent.snapshot(null, null); // parent.layout(); // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/test/java/de/tesis/dynaware/grapheditor/utils/ResizableBoxTest.java import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.dragBy; import static de.tesis.dynaware.grapheditor.utils.FXTestUtils.forceLayoutUpdate; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import de.tesis.dynaware.grapheditor.EditorElement; import javafx.scene.layout.Pane; package de.tesis.dynaware.grapheditor.utils; public class ResizableBoxTest { @ClassRule public static JavaFXThreadingRule javaFXThreadingRule = new JavaFXThreadingRule(); private final static double BOX_WIDTH = 240; private final static double BOX_HEIGHT = 100; private final static double BOX_INITIAL_X = 60; private final static double BOX_INITIAL_Y = 60; private final static double BOX_RESIZE_BORDER_TOLERANCE = 1; private final ResizableBox box = new ResizableBox(EditorElement.NODE); private final Pane container = new Pane(); private final GraphEditorProperties properties = new GraphEditorProperties(); @Before public void setUp() throws Exception { box.setEditorProperties(properties); box.resize(BOX_WIDTH, BOX_HEIGHT); box.setLayoutX(BOX_INITIAL_X); box.setLayoutY(BOX_INITIAL_Y); container.setPrefSize(360, 300); container.autosize(); container.getChildren().add(box); forceLayoutUpdate(container); } @Test public void testResize_UpperLeftCorner() {
dragBy(box, 24, 33);
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEditorProperties.java
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java // public class GraphEventManagerImpl implements GraphEventManager // { // // private GraphInputGesture gesture; // private Object owner; // // @Override // public boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner) // { // if (!canOverwrite(owner, pOwner)) // { // return false; // } // if (canActivate(pGesture, pEvent)) // { // gesture = pGesture; // owner = pOwner; // return true; // } // // ELSE: // return false; // } // // private boolean canActivate(final GraphInputGesture pGesture, final Event pEvent) // { // final GraphInputGesture current = gesture; // if (current == pGesture) // { // return true; // } // else if (current == null) // { // final boolean isTouch = pEvent instanceof TouchEvent || pEvent instanceof MouseEvent me && me.isSynthesized() // || pEvent instanceof ScrollEvent se && se.getTouchCount() > 0; // if (!isTouch) // { // return switch (pGesture) // { // case PAN -> pEvent instanceof ScrollEvent se && !se.isControlDown() // || pEvent instanceof MouseEvent me && me.isSecondaryButtonDown(); // case ZOOM -> pEvent instanceof ScrollEvent se && se.isControlDown(); // case SELECT, CONNECT, MOVE, RESIZE -> pEvent instanceof MouseEvent me && // me.isPrimaryButtonDown(); // }; // } // else // { // return switch (pGesture) // { // case ZOOM -> pEvent instanceof ZoomEvent; // case PAN -> pEvent instanceof TouchEvent && ((TouchEvent) pEvent).getTouchCount() > 1; // case SELECT, CONNECT, MOVE, RESIZE -> true; // }; // } // } // return false; // } // // @Override // public boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner) // { // if (gesture == pExpected && (owner == pOwner || !isVisible(owner))) // { // gesture = null; // owner = null; // return true; // } // return false; // } // // private static boolean canOverwrite(final Object pExisting, final Object pCandidate) // { // if (pExisting == pCandidate) // { // return true; // } // if (pCandidate == null) // { // return false; // } // return pExisting == null || !isVisible(pExisting); // } // // private static boolean isVisible(final Object pNode) // { // if (pNode != null) // { // if (pNode instanceof Node n) // { // return n.isVisible() && n.getParent() != null && n.getScene() != null; // } // return true; // } // // ELSE: null // return false; // } // }
import java.util.EnumMap; import java.util.Map; import java.util.Objects; import de.tesis.dynaware.grapheditor.EditorElement; import de.tesis.dynaware.grapheditor.impl.GraphEventManagerImpl; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.event.Event;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * General properties for the graph editor. * * <p> * For example, should the editor have 'bounds', or should objects be draggable outside the editor area? * </p> * * <p> * If a bound is <b>active</b>, objects that are dragged or resized in the editor should stop when they hit the edge, * and the editor region will not try to grow in size. Otherwise it will grow up to its max size. * </p> * * <p> * Also stores properties for whether the grid is visible and/or snap-to-grid is on. * </p> */ public class GraphEditorProperties implements GraphEventManager { /** * The default max width of the editor region, set on startup. */ public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; /** * The default max height of the editor region, set on startup. */ public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; public static final double DEFAULT_BOUND_VALUE = 15; public static final double DEFAULT_GRID_SPACING = 12; // The distance from the editor edge at which the objects should stop when dragged / resized. private double northBoundValue = DEFAULT_BOUND_VALUE; private double southBoundValue = DEFAULT_BOUND_VALUE; private double eastBoundValue = DEFAULT_BOUND_VALUE; private double westBoundValue = DEFAULT_BOUND_VALUE; // Off by default. private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, "gridVisible"); //$NON-NLS-1$ private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, "snapToGrid"); //$NON-NLS-1$ private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, "gridSpacing", DEFAULT_GRID_SPACING); //$NON-NLS-1$
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java // public class GraphEventManagerImpl implements GraphEventManager // { // // private GraphInputGesture gesture; // private Object owner; // // @Override // public boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner) // { // if (!canOverwrite(owner, pOwner)) // { // return false; // } // if (canActivate(pGesture, pEvent)) // { // gesture = pGesture; // owner = pOwner; // return true; // } // // ELSE: // return false; // } // // private boolean canActivate(final GraphInputGesture pGesture, final Event pEvent) // { // final GraphInputGesture current = gesture; // if (current == pGesture) // { // return true; // } // else if (current == null) // { // final boolean isTouch = pEvent instanceof TouchEvent || pEvent instanceof MouseEvent me && me.isSynthesized() // || pEvent instanceof ScrollEvent se && se.getTouchCount() > 0; // if (!isTouch) // { // return switch (pGesture) // { // case PAN -> pEvent instanceof ScrollEvent se && !se.isControlDown() // || pEvent instanceof MouseEvent me && me.isSecondaryButtonDown(); // case ZOOM -> pEvent instanceof ScrollEvent se && se.isControlDown(); // case SELECT, CONNECT, MOVE, RESIZE -> pEvent instanceof MouseEvent me && // me.isPrimaryButtonDown(); // }; // } // else // { // return switch (pGesture) // { // case ZOOM -> pEvent instanceof ZoomEvent; // case PAN -> pEvent instanceof TouchEvent && ((TouchEvent) pEvent).getTouchCount() > 1; // case SELECT, CONNECT, MOVE, RESIZE -> true; // }; // } // } // return false; // } // // @Override // public boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner) // { // if (gesture == pExpected && (owner == pOwner || !isVisible(owner))) // { // gesture = null; // owner = null; // return true; // } // return false; // } // // private static boolean canOverwrite(final Object pExisting, final Object pCandidate) // { // if (pExisting == pCandidate) // { // return true; // } // if (pCandidate == null) // { // return false; // } // return pExisting == null || !isVisible(pExisting); // } // // private static boolean isVisible(final Object pNode) // { // if (pNode != null) // { // if (pNode instanceof Node n) // { // return n.isVisible() && n.getParent() != null && n.getScene() != null; // } // return true; // } // // ELSE: null // return false; // } // } // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEditorProperties.java import java.util.EnumMap; import java.util.Map; import java.util.Objects; import de.tesis.dynaware.grapheditor.EditorElement; import de.tesis.dynaware.grapheditor.impl.GraphEventManagerImpl; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.event.Event; /* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * General properties for the graph editor. * * <p> * For example, should the editor have 'bounds', or should objects be draggable outside the editor area? * </p> * * <p> * If a bound is <b>active</b>, objects that are dragged or resized in the editor should stop when they hit the edge, * and the editor region will not try to grow in size. Otherwise it will grow up to its max size. * </p> * * <p> * Also stores properties for whether the grid is visible and/or snap-to-grid is on. * </p> */ public class GraphEditorProperties implements GraphEventManager { /** * The default max width of the editor region, set on startup. */ public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; /** * The default max height of the editor region, set on startup. */ public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; public static final double DEFAULT_BOUND_VALUE = 15; public static final double DEFAULT_GRID_SPACING = 12; // The distance from the editor edge at which the objects should stop when dragged / resized. private double northBoundValue = DEFAULT_BOUND_VALUE; private double southBoundValue = DEFAULT_BOUND_VALUE; private double eastBoundValue = DEFAULT_BOUND_VALUE; private double westBoundValue = DEFAULT_BOUND_VALUE; // Off by default. private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, "gridVisible"); //$NON-NLS-1$ private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, "snapToGrid"); //$NON-NLS-1$ private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, "gridSpacing", DEFAULT_GRID_SPACING); //$NON-NLS-1$
private final Map<EditorElement, BooleanProperty> readOnly = new EnumMap<>(EditorElement.class);
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEditorProperties.java
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java // public class GraphEventManagerImpl implements GraphEventManager // { // // private GraphInputGesture gesture; // private Object owner; // // @Override // public boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner) // { // if (!canOverwrite(owner, pOwner)) // { // return false; // } // if (canActivate(pGesture, pEvent)) // { // gesture = pGesture; // owner = pOwner; // return true; // } // // ELSE: // return false; // } // // private boolean canActivate(final GraphInputGesture pGesture, final Event pEvent) // { // final GraphInputGesture current = gesture; // if (current == pGesture) // { // return true; // } // else if (current == null) // { // final boolean isTouch = pEvent instanceof TouchEvent || pEvent instanceof MouseEvent me && me.isSynthesized() // || pEvent instanceof ScrollEvent se && se.getTouchCount() > 0; // if (!isTouch) // { // return switch (pGesture) // { // case PAN -> pEvent instanceof ScrollEvent se && !se.isControlDown() // || pEvent instanceof MouseEvent me && me.isSecondaryButtonDown(); // case ZOOM -> pEvent instanceof ScrollEvent se && se.isControlDown(); // case SELECT, CONNECT, MOVE, RESIZE -> pEvent instanceof MouseEvent me && // me.isPrimaryButtonDown(); // }; // } // else // { // return switch (pGesture) // { // case ZOOM -> pEvent instanceof ZoomEvent; // case PAN -> pEvent instanceof TouchEvent && ((TouchEvent) pEvent).getTouchCount() > 1; // case SELECT, CONNECT, MOVE, RESIZE -> true; // }; // } // } // return false; // } // // @Override // public boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner) // { // if (gesture == pExpected && (owner == pOwner || !isVisible(owner))) // { // gesture = null; // owner = null; // return true; // } // return false; // } // // private static boolean canOverwrite(final Object pExisting, final Object pCandidate) // { // if (pExisting == pCandidate) // { // return true; // } // if (pCandidate == null) // { // return false; // } // return pExisting == null || !isVisible(pExisting); // } // // private static boolean isVisible(final Object pNode) // { // if (pNode != null) // { // if (pNode instanceof Node n) // { // return n.isVisible() && n.getParent() != null && n.getScene() != null; // } // return true; // } // // ELSE: null // return false; // } // }
import java.util.EnumMap; import java.util.Map; import java.util.Objects; import de.tesis.dynaware.grapheditor.EditorElement; import de.tesis.dynaware.grapheditor.impl.GraphEventManagerImpl; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.event.Event;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * General properties for the graph editor. * * <p> * For example, should the editor have 'bounds', or should objects be draggable outside the editor area? * </p> * * <p> * If a bound is <b>active</b>, objects that are dragged or resized in the editor should stop when they hit the edge, * and the editor region will not try to grow in size. Otherwise it will grow up to its max size. * </p> * * <p> * Also stores properties for whether the grid is visible and/or snap-to-grid is on. * </p> */ public class GraphEditorProperties implements GraphEventManager { /** * The default max width of the editor region, set on startup. */ public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; /** * The default max height of the editor region, set on startup. */ public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; public static final double DEFAULT_BOUND_VALUE = 15; public static final double DEFAULT_GRID_SPACING = 12; // The distance from the editor edge at which the objects should stop when dragged / resized. private double northBoundValue = DEFAULT_BOUND_VALUE; private double southBoundValue = DEFAULT_BOUND_VALUE; private double eastBoundValue = DEFAULT_BOUND_VALUE; private double westBoundValue = DEFAULT_BOUND_VALUE; // Off by default. private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, "gridVisible"); //$NON-NLS-1$ private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, "snapToGrid"); //$NON-NLS-1$ private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, "gridSpacing", DEFAULT_GRID_SPACING); //$NON-NLS-1$ private final Map<EditorElement, BooleanProperty> readOnly = new EnumMap<>(EditorElement.class); private final ObservableMap<String, String> customProperties = FXCollections.observableHashMap();
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // // Path: api/src/main/java/de/tesis/dynaware/grapheditor/impl/GraphEventManagerImpl.java // public class GraphEventManagerImpl implements GraphEventManager // { // // private GraphInputGesture gesture; // private Object owner; // // @Override // public boolean activateGesture(final GraphInputGesture pGesture, final Event pEvent, final Object pOwner) // { // if (!canOverwrite(owner, pOwner)) // { // return false; // } // if (canActivate(pGesture, pEvent)) // { // gesture = pGesture; // owner = pOwner; // return true; // } // // ELSE: // return false; // } // // private boolean canActivate(final GraphInputGesture pGesture, final Event pEvent) // { // final GraphInputGesture current = gesture; // if (current == pGesture) // { // return true; // } // else if (current == null) // { // final boolean isTouch = pEvent instanceof TouchEvent || pEvent instanceof MouseEvent me && me.isSynthesized() // || pEvent instanceof ScrollEvent se && se.getTouchCount() > 0; // if (!isTouch) // { // return switch (pGesture) // { // case PAN -> pEvent instanceof ScrollEvent se && !se.isControlDown() // || pEvent instanceof MouseEvent me && me.isSecondaryButtonDown(); // case ZOOM -> pEvent instanceof ScrollEvent se && se.isControlDown(); // case SELECT, CONNECT, MOVE, RESIZE -> pEvent instanceof MouseEvent me && // me.isPrimaryButtonDown(); // }; // } // else // { // return switch (pGesture) // { // case ZOOM -> pEvent instanceof ZoomEvent; // case PAN -> pEvent instanceof TouchEvent && ((TouchEvent) pEvent).getTouchCount() > 1; // case SELECT, CONNECT, MOVE, RESIZE -> true; // }; // } // } // return false; // } // // @Override // public boolean finishGesture(final GraphInputGesture pExpected, final Object pOwner) // { // if (gesture == pExpected && (owner == pOwner || !isVisible(owner))) // { // gesture = null; // owner = null; // return true; // } // return false; // } // // private static boolean canOverwrite(final Object pExisting, final Object pCandidate) // { // if (pExisting == pCandidate) // { // return true; // } // if (pCandidate == null) // { // return false; // } // return pExisting == null || !isVisible(pExisting); // } // // private static boolean isVisible(final Object pNode) // { // if (pNode != null) // { // if (pNode instanceof Node n) // { // return n.isVisible() && n.getParent() != null && n.getScene() != null; // } // return true; // } // // ELSE: null // return false; // } // } // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/GraphEditorProperties.java import java.util.EnumMap; import java.util.Map; import java.util.Objects; import de.tesis.dynaware.grapheditor.EditorElement; import de.tesis.dynaware.grapheditor.impl.GraphEventManagerImpl; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.event.Event; /* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * General properties for the graph editor. * * <p> * For example, should the editor have 'bounds', or should objects be draggable outside the editor area? * </p> * * <p> * If a bound is <b>active</b>, objects that are dragged or resized in the editor should stop when they hit the edge, * and the editor region will not try to grow in size. Otherwise it will grow up to its max size. * </p> * * <p> * Also stores properties for whether the grid is visible and/or snap-to-grid is on. * </p> */ public class GraphEditorProperties implements GraphEventManager { /** * The default max width of the editor region, set on startup. */ public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; /** * The default max height of the editor region, set on startup. */ public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; public static final double DEFAULT_BOUND_VALUE = 15; public static final double DEFAULT_GRID_SPACING = 12; // The distance from the editor edge at which the objects should stop when dragged / resized. private double northBoundValue = DEFAULT_BOUND_VALUE; private double southBoundValue = DEFAULT_BOUND_VALUE; private double eastBoundValue = DEFAULT_BOUND_VALUE; private double westBoundValue = DEFAULT_BOUND_VALUE; // Off by default. private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, "gridVisible"); //$NON-NLS-1$ private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, "snapToGrid"); //$NON-NLS-1$ private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, "gridSpacing", DEFAULT_GRID_SPACING); //$NON-NLS-1$ private final Map<EditorElement, BooleanProperty> readOnly = new EnumMap<>(EditorElement.class); private final ObservableMap<String, String> customProperties = FXCollections.observableHashMap();
private final GraphEventManager eventManager = new GraphEventManagerImpl();
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/utils/ResizableBox.java
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // }
import de.tesis.dynaware.grapheditor.EditorElement; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * A draggable, resizable box that can display children. * * <p> * See {@link DraggableBox} for more information. * </p> */ public class ResizableBox extends DraggableBox { private static final int DEFAULT_RESIZE_BORDER_TOLERANCE = 8; private double lastWidth; private double lastHeight; private RectangleMouseRegion lastMouseRegion; private boolean mouseInPositionForResize; /** * Creates an empty resizable box. * * @param pType * {@link EditorElement} */
// Path: api/src/main/java/de/tesis/dynaware/grapheditor/EditorElement.java // public enum EditorElement // { // CONNECTOR, // NODE, // JOINT; // } // Path: api/src/main/java/de/tesis/dynaware/grapheditor/utils/ResizableBox.java import de.tesis.dynaware.grapheditor.EditorElement; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; /* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.utils; /** * A draggable, resizable box that can display children. * * <p> * See {@link DraggableBox} for more information. * </p> */ public class ResizableBox extends DraggableBox { private static final int DEFAULT_RESIZE_BORDER_TOLERANCE = 8; private double lastWidth; private double lastHeight; private RectangleMouseRegion lastMouseRegion; private boolean mouseInPositionForResize; /** * Creates an empty resizable box. * * @param pType * {@link EditorElement} */
public ResizableBox(final EditorElement pType)
opencb/bionetdb
bionetdb-core/src/main/java/org/opencb/bionetdb/core/io/SbmlParser.java
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/network/Network.java // public class Network extends Graph { // // private String id; // private String name; // private String description; // // private Map<String, Object> attributes; // // private long numNodes; // private long numRelations; // // public Network() { // this("", "", ""); // } // // public Network(String id, String name, String description) { // super(); // this.id = id; // this.name = name; // this.description = description; // // attributes = new HashMap<>(); // } // // public void write(File file) throws FileNotFoundException, JsonProcessingException { // Network network = new Network(id, name, description); // network.setAttributes(attributes); // network.setNumNodes(nodes.size()); // network.setNumRelations(relations.size()); // // ObjectMapper mapper = new ObjectMapper(); // mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); // // PrintWriter pw = new PrintWriter(file); // // pw.println(mapper.writer().writeValueAsString(network)); // for (Node node: nodes) { // pw.println(mapper.writer().writeValueAsString(node)); // } // for (Relation relation: relations) { // pw.println(mapper.writer().writeValueAsString(relation)); // } // // pw.close(); // // // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Network{"); // sb.append("id='").append(id).append('\''); // sb.append(", name='").append(name).append('\''); // sb.append(", description='").append(description).append('\''); // sb.append(", nodes=").append(nodes); // sb.append(", relations=").append(relations); // sb.append(", attributes=").append(attributes); // sb.append('}'); // return sb.toString(); // } // // public String getId() { // return id; // } // // public Network setId(String id) { // this.id = id; // return this; // } // // public String getName() { // return name; // } // // public Network setName(String name) { // this.name = name; // return this; // } // // public String getDescription() { // return description; // } // // public Network setDescription(String description) { // this.description = description; // return this; // } // // public Map<String, Object> getAttributes() { // return attributes; // } // // public Network setAttributes(Map<String, Object> attributes) { // this.attributes = attributes; // return this; // } // // public Network setNumNodes(long numNodes) { // this.numNodes = numNodes; // return this; // } // // public Network setNumRelations(long numRelations) { // this.numRelations = numRelations; // return this; // } // }
import org.opencb.bionetdb.core.models.network.Network; import java.io.IOException; import java.nio.file.Path;
+ " which one you are using) to make sure it list the" + " directories needed to find the " + System.mapLibraryName("sbmlj") + " library file and" + " libraries it depends upon (e.g., the XML parser)."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file 'libsbmlj.jar'." + " It is likely that your -classpath command line " + " setting or your CLASSPATH environment variable " + " do not include the file 'libsbmlj.jar'."); e.printStackTrace(); System.exit(1); } catch (SecurityException e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Could not load the libSBML library files due to a" + " security exception.\n"); System.exit(1); } } private static final String REACTOME_FEAT = "reactome."; public SbmlParser() { init(); } private void init() { }
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/network/Network.java // public class Network extends Graph { // // private String id; // private String name; // private String description; // // private Map<String, Object> attributes; // // private long numNodes; // private long numRelations; // // public Network() { // this("", "", ""); // } // // public Network(String id, String name, String description) { // super(); // this.id = id; // this.name = name; // this.description = description; // // attributes = new HashMap<>(); // } // // public void write(File file) throws FileNotFoundException, JsonProcessingException { // Network network = new Network(id, name, description); // network.setAttributes(attributes); // network.setNumNodes(nodes.size()); // network.setNumRelations(relations.size()); // // ObjectMapper mapper = new ObjectMapper(); // mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); // // PrintWriter pw = new PrintWriter(file); // // pw.println(mapper.writer().writeValueAsString(network)); // for (Node node: nodes) { // pw.println(mapper.writer().writeValueAsString(node)); // } // for (Relation relation: relations) { // pw.println(mapper.writer().writeValueAsString(relation)); // } // // pw.close(); // // // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Network{"); // sb.append("id='").append(id).append('\''); // sb.append(", name='").append(name).append('\''); // sb.append(", description='").append(description).append('\''); // sb.append(", nodes=").append(nodes); // sb.append(", relations=").append(relations); // sb.append(", attributes=").append(attributes); // sb.append('}'); // return sb.toString(); // } // // public String getId() { // return id; // } // // public Network setId(String id) { // this.id = id; // return this; // } // // public String getName() { // return name; // } // // public Network setName(String name) { // this.name = name; // return this; // } // // public String getDescription() { // return description; // } // // public Network setDescription(String description) { // this.description = description; // return this; // } // // public Map<String, Object> getAttributes() { // return attributes; // } // // public Network setAttributes(Map<String, Object> attributes) { // this.attributes = attributes; // return this; // } // // public Network setNumNodes(long numNodes) { // this.numNodes = numNodes; // return this; // } // // public Network setNumRelations(long numRelations) { // this.numRelations = numRelations; // return this; // } // } // Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/io/SbmlParser.java import org.opencb.bionetdb.core.models.network.Network; import java.io.IOException; import java.nio.file.Path; + " which one you are using) to make sure it list the" + " directories needed to find the " + System.mapLibraryName("sbmlj") + " library file and" + " libraries it depends upon (e.g., the XML parser)."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file 'libsbmlj.jar'." + " It is likely that your -classpath command line " + " setting or your CLASSPATH environment variable " + " do not include the file 'libsbmlj.jar'."); e.printStackTrace(); System.exit(1); } catch (SecurityException e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Could not load the libSBML library files due to a" + " security exception.\n"); System.exit(1); } } private static final String REACTOME_FEAT = "reactome."; public SbmlParser() { init(); } private void init() { }
public Network parse(Path path) throws IOException {
opencb/bionetdb
bionetdb-core/src/main/java/org/opencb/bionetdb/core/io/ExpressionParser.java
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/Expression.java // public class Expression { // // // TODO: upregulated can be 0 (not upregulated) or 1 (upregulated). Include downregulated? // // private String id; // private double expression; // private double pvalue; // private double odds; // private int upregulated; // // public Expression() { // this(""); // } // // public Expression(String id) { // this.id = id; // this.expression = -1; // this.pvalue = -1; // this.odds = -1; // this.upregulated = -1; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Expression{"); // sb.append("id='").append(id).append('\''); // sb.append(", expression=").append(expression); // sb.append(", pvalue=").append(pvalue); // sb.append(", odds=").append(odds); // sb.append(", upregulated=").append(upregulated); // sb.append('}'); // return sb.toString(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public double getExpression() { // return expression; // } // // public void setExpression(double expression) { // this.expression = expression; // } // // public double getPvalue() { // return pvalue; // } // // public void setPvalue(double pvalue) { // this.pvalue = pvalue; // } // // public double getOdds() { // return odds; // } // // public void setOdds(double odds) { // this.odds = odds; // } // // public int getUpregulated() { // return upregulated; // } // // public void setUpregulated(int upregulated) { // this.upregulated = upregulated; // } // // }
import org.opencb.bionetdb.core.models.Expression; import org.opencb.commons.utils.FileUtils; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package org.opencb.bionetdb.core.io; /** * Created by pfurio on 8/9/15. */ public class ExpressionParser { private Map<String, Map<String, String>> myFiles; public ExpressionParser(Path metadata) throws IOException { FileUtils.checkFile(metadata); myFiles = new HashMap<>(); List<String> allLines = Files.readAllLines(metadata); for (String line : allLines) { String[] fields = line.split("\t"); Map<String, String> timeSeries; if (myFiles.containsKey(fields[0])) { timeSeries = myFiles.get(fields[0]); } else { timeSeries = new HashMap<>(); } timeSeries.put(fields[1], metadata.getParent().toString() + "/" + fields[2]); if (!myFiles.containsKey(fields[0])) { myFiles.put(fields[0], timeSeries); } } }
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/Expression.java // public class Expression { // // // TODO: upregulated can be 0 (not upregulated) or 1 (upregulated). Include downregulated? // // private String id; // private double expression; // private double pvalue; // private double odds; // private int upregulated; // // public Expression() { // this(""); // } // // public Expression(String id) { // this.id = id; // this.expression = -1; // this.pvalue = -1; // this.odds = -1; // this.upregulated = -1; // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Expression{"); // sb.append("id='").append(id).append('\''); // sb.append(", expression=").append(expression); // sb.append(", pvalue=").append(pvalue); // sb.append(", odds=").append(odds); // sb.append(", upregulated=").append(upregulated); // sb.append('}'); // return sb.toString(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public double getExpression() { // return expression; // } // // public void setExpression(double expression) { // this.expression = expression; // } // // public double getPvalue() { // return pvalue; // } // // public void setPvalue(double pvalue) { // this.pvalue = pvalue; // } // // public double getOdds() { // return odds; // } // // public void setOdds(double odds) { // this.odds = odds; // } // // public int getUpregulated() { // return upregulated; // } // // public void setUpregulated(int upregulated) { // this.upregulated = upregulated; // } // // } // Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/io/ExpressionParser.java import org.opencb.bionetdb.core.models.Expression; import org.opencb.commons.utils.FileUtils; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package org.opencb.bionetdb.core.io; /** * Created by pfurio on 8/9/15. */ public class ExpressionParser { private Map<String, Map<String, String>> myFiles; public ExpressionParser(Path metadata) throws IOException { FileUtils.checkFile(metadata); myFiles = new HashMap<>(); List<String> allLines = Files.readAllLines(metadata); for (String line : allLines) { String[] fields = line.split("\t"); Map<String, String> timeSeries; if (myFiles.containsKey(fields[0])) { timeSeries = myFiles.get(fields[0]); } else { timeSeries = new HashMap<>(); } timeSeries.put(fields[1], metadata.getParent().toString() + "/" + fields[2]); if (!myFiles.containsKey(fields[0])) { myFiles.put(fields[0], timeSeries); } } }
public List<Expression> parse(String tissue, String time) throws IOException {
opencb/bionetdb
bionetdb-server/src/main/java/org/opencb/bionetdb/server/rest/AnalysisWSServer.java
// Path: bionetdb-server/src/main/java/org/opencb/bionetdb/server/exception/VersionException.java // @SuppressWarnings("serial") // public class VersionException extends Exception { // // public VersionException(String msg) { // super(msg); // } // // }
import io.swagger.annotations.Api; import org.opencb.bionetdb.server.exception.VersionException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo;
package org.opencb.bionetdb.server.rest; @Path("/{apiVersion}/analysis") @Produces("application/json") @Api(value = "Analysis", position = 1, description = "Methods for working with 'nodes'") public class AnalysisWSServer extends GenericRestWSServer { public AnalysisWSServer(@Context UriInfo uriInfo,
// Path: bionetdb-server/src/main/java/org/opencb/bionetdb/server/exception/VersionException.java // @SuppressWarnings("serial") // public class VersionException extends Exception { // // public VersionException(String msg) { // super(msg); // } // // } // Path: bionetdb-server/src/main/java/org/opencb/bionetdb/server/rest/AnalysisWSServer.java import io.swagger.annotations.Api; import org.opencb.bionetdb.server.exception.VersionException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; package org.opencb.bionetdb.server.rest; @Path("/{apiVersion}/analysis") @Produces("application/json") @Api(value = "Analysis", position = 1, description = "Methods for working with 'nodes'") public class AnalysisWSServer extends GenericRestWSServer { public AnalysisWSServer(@Context UriInfo uriInfo,
@Context HttpServletRequest hsr) throws VersionException {
opencb/bionetdb
bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/network/NetworkManager.java
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/exceptions/BioNetDBException.java // public class BioNetDBException extends Exception { // // public BioNetDBException(String message) { // super(message); // } // // public BioNetDBException(String message, Throwable cause) { // super(message, cause); // } // // public BioNetDBException(Throwable cause) { // super(cause); // } // // }
import org.apache.commons.collections4.CollectionUtils; import org.opencb.bionetdb.core.exceptions.BioNetDBException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
} public Node getNode(long uid) { return network.getNodes().get(nodesIndex.get(uid)); } public List<Node> getNodes() { return network.getNodes(); } public List<Node> getNodes(String id) { List<Node> nodes = new ArrayList<>(); for (long uid: nodesUids.get(id)) { nodes.add(getNode(uid)); } return nodes; } public List<Node> getNodes(Node.Label label) { List<Node> nodes = new ArrayList<>(); for (Node node: network.getNodes()) { if (CollectionUtils.isNotEmpty(node.getLabels())) { if (node.getLabels().contains(label)) { nodes.add(node); } } } return nodes; }
// Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/exceptions/BioNetDBException.java // public class BioNetDBException extends Exception { // // public BioNetDBException(String message) { // super(message); // } // // public BioNetDBException(String message, Throwable cause) { // super(message, cause); // } // // public BioNetDBException(Throwable cause) { // super(cause); // } // // } // Path: bionetdb-core/src/main/java/org/opencb/bionetdb/core/models/network/NetworkManager.java import org.apache.commons.collections4.CollectionUtils; import org.opencb.bionetdb.core.exceptions.BioNetDBException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; } public Node getNode(long uid) { return network.getNodes().get(nodesIndex.get(uid)); } public List<Node> getNodes() { return network.getNodes(); } public List<Node> getNodes(String id) { List<Node> nodes = new ArrayList<>(); for (long uid: nodesUids.get(id)) { nodes.add(getNode(uid)); } return nodes; } public List<Node> getNodes(Node.Label label) { List<Node> nodes = new ArrayList<>(); for (Node node: network.getNodes()) { if (CollectionUtils.isNotEmpty(node.getLabels())) { if (node.getLabels().contains(label)) { nodes.add(node); } } } return nodes; }
public void setNode(Node node) throws BioNetDBException {
opencb/bionetdb
bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/cache/Cache.java
// Path: bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/RocksDbManager.java // public class RocksDbManager { // // private int maxOpenFiles = -1; // // public RocksDbManager() { // this(1000); // } // // public RocksDbManager(int maxOpenFiles) { // this.maxOpenFiles = maxOpenFiles; // } // // public RocksDB getDBConnection(String dbLocation, boolean forceCreate) { // boolean indexingNeeded = forceCreate || !Files.exists(Paths.get(dbLocation)); // // // A static method that loads the RocksDB C++ library. // RocksDB.loadLibrary(); // // // The OptionsFilter class contains a set of configurable DB options that determines the behavior of a database. // Options options = new Options().setCreateIfMissing(true); // if (maxOpenFiles > 0) { // options.setMaxOpenFiles(maxOpenFiles); // } // // RocksDB db; // try { // // A factory method that returns a RocksDB instance // if (indexingNeeded) { // db = RocksDB.open(options, dbLocation); // } else { // db = RocksDB.openReadOnly(options, dbLocation); // } // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // db = null; // } // // return db; // } // // public boolean putString(String key, String value, RocksDB db) { // try { // // Add string value into the database // db.put(key.getBytes(), value.getBytes()); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public boolean putLong(String key, Long value, RocksDB db) { // try { // // Add boolean value into the database // db.put(key.getBytes(), Longs.toByteArray(value)); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public boolean putBoolean(String key, Boolean value, RocksDB db) { // try { // // Add boolean value into the database // db.put(key.getBytes(), new byte[]{(byte) (value ? 1 : 0)}); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public String getString(String key, RocksDB db) { // try { // // Get string value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return new String(value); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // public Long getLong(String key, RocksDB db) { // try { // // Get string value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return Longs.fromByteArray(value); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // // public Boolean getBoolean(String key, RocksDB db) { // try { // // Get boolean value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return (value[0] == 1 ? true : false); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // public void close(RocksDB db) { // db.close(); // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import org.apache.commons.lang3.StringUtils; import org.opencb.bionetdb.lib.utils.RocksDbManager; import org.rocksdb.RocksDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Paths;
package org.opencb.bionetdb.lib.utils.cache; public abstract class Cache<T> { protected String objFilename; protected String xrefObjFilename; protected RocksDB objRocksDb; protected RocksDB xrefObjRocksDb;
// Path: bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/RocksDbManager.java // public class RocksDbManager { // // private int maxOpenFiles = -1; // // public RocksDbManager() { // this(1000); // } // // public RocksDbManager(int maxOpenFiles) { // this.maxOpenFiles = maxOpenFiles; // } // // public RocksDB getDBConnection(String dbLocation, boolean forceCreate) { // boolean indexingNeeded = forceCreate || !Files.exists(Paths.get(dbLocation)); // // // A static method that loads the RocksDB C++ library. // RocksDB.loadLibrary(); // // // The OptionsFilter class contains a set of configurable DB options that determines the behavior of a database. // Options options = new Options().setCreateIfMissing(true); // if (maxOpenFiles > 0) { // options.setMaxOpenFiles(maxOpenFiles); // } // // RocksDB db; // try { // // A factory method that returns a RocksDB instance // if (indexingNeeded) { // db = RocksDB.open(options, dbLocation); // } else { // db = RocksDB.openReadOnly(options, dbLocation); // } // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // db = null; // } // // return db; // } // // public boolean putString(String key, String value, RocksDB db) { // try { // // Add string value into the database // db.put(key.getBytes(), value.getBytes()); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public boolean putLong(String key, Long value, RocksDB db) { // try { // // Add boolean value into the database // db.put(key.getBytes(), Longs.toByteArray(value)); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public boolean putBoolean(String key, Boolean value, RocksDB db) { // try { // // Add boolean value into the database // db.put(key.getBytes(), new byte[]{(byte) (value ? 1 : 0)}); // return true; // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return false; // } // } // // public String getString(String key, RocksDB db) { // try { // // Get string value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return new String(value); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // public Long getLong(String key, RocksDB db) { // try { // // Get string value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return Longs.fromByteArray(value); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // // public Boolean getBoolean(String key, RocksDB db) { // try { // // Get boolean value from the database // byte[] value = db.get(key.getBytes()); // if (value == null) { // return null; // } // return (value[0] == 1 ? true : false); // } catch (RocksDBException e) { // // Do some error handling // e.printStackTrace(); // return null; // } // } // // public void close(RocksDB db) { // db.close(); // } // } // Path: bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/cache/Cache.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import org.apache.commons.lang3.StringUtils; import org.opencb.bionetdb.lib.utils.RocksDbManager; import org.rocksdb.RocksDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Paths; package org.opencb.bionetdb.lib.utils.cache; public abstract class Cache<T> { protected String objFilename; protected String xrefObjFilename; protected RocksDB objRocksDb; protected RocksDB xrefObjRocksDb;
protected RocksDbManager rocksDbManager;
mingzhou/LogisticsPlatform
Client/LogisticsPlatform_stable/app/src/main/java/com/logistics/module/LogisticsModule.java
// Path: Client/LogisticsPlatform_stable/app/src/main/java/com/logistics/utils/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // private static final String DATABASE_NAME = "logistics.db"; // // /** // * 数据库的版本,更新一次数据库,会把原来的是数据都删掉(TODO 修改成升级策略) // * 更新的做法,是把DATABASE_VERSION加1 // */ // private static final int DATABASE_VERSION = 1; // // private Dao<MyData, Integer> mydataDao; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // /** // * 第一次安装的时候创建数据库 // */ // @Override // public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { // try { // //TableUtils.createTable(connectionSource, Account.class); // TableUtils.createTable(connectionSource, MyData.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // /** // * APP更新的时候更新数据库 // */ // @Override // public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, // int newVersion) { // try { // //TableUtils.dropTable(connectionSource, Account.class, true); // TableUtils.dropTable(connectionSource, MyData.class, true); // onCreate(db, connectionSource); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public Dao<MyData, Integer> getMyDataDao() throws SQLException { // if (mydataDao == null) { // mydataDao = getDao(MyData.class); // } // return mydataDao; // } // // @Override // public void close() { // // TODO Auto-generated method stub // super.close(); // } // // // }
import com.google.inject.AbstractModule; import com.logistics.utils.DatabaseHelper;
package com.logistics.module; /** * 模块化安装各个组件 * 实现了接口和服务的分离 * @author Mingzhou Zhuang ([email protected]) * */ public class LogisticsModule extends AbstractModule { @Override protected void configure() { // 指定要使用的interface是由哪个具体的service实现的 // 如果直接使用具体的service,当然就不需要再绑定了,比如这里的com.mz.astroboy.entity.internal.ContextInfo
// Path: Client/LogisticsPlatform_stable/app/src/main/java/com/logistics/utils/DatabaseHelper.java // public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // // private static final String DATABASE_NAME = "logistics.db"; // // /** // * 数据库的版本,更新一次数据库,会把原来的是数据都删掉(TODO 修改成升级策略) // * 更新的做法,是把DATABASE_VERSION加1 // */ // private static final int DATABASE_VERSION = 1; // // private Dao<MyData, Integer> mydataDao; // // public DatabaseHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // /** // * 第一次安装的时候创建数据库 // */ // @Override // public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { // try { // //TableUtils.createTable(connectionSource, Account.class); // TableUtils.createTable(connectionSource, MyData.class); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // /** // * APP更新的时候更新数据库 // */ // @Override // public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, // int newVersion) { // try { // //TableUtils.dropTable(connectionSource, Account.class, true); // TableUtils.dropTable(connectionSource, MyData.class, true); // onCreate(db, connectionSource); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public Dao<MyData, Integer> getMyDataDao() throws SQLException { // if (mydataDao == null) { // mydataDao = getDao(MyData.class); // } // return mydataDao; // } // // @Override // public void close() { // // TODO Auto-generated method stub // super.close(); // } // // // } // Path: Client/LogisticsPlatform_stable/app/src/main/java/com/logistics/module/LogisticsModule.java import com.google.inject.AbstractModule; import com.logistics.utils.DatabaseHelper; package com.logistics.module; /** * 模块化安装各个组件 * 实现了接口和服务的分离 * @author Mingzhou Zhuang ([email protected]) * */ public class LogisticsModule extends AbstractModule { @Override protected void configure() { // 指定要使用的interface是由哪个具体的service实现的 // 如果直接使用具体的service,当然就不需要再绑定了,比如这里的com.mz.astroboy.entity.internal.ContextInfo
requestStaticInjection(DatabaseHelper.class);
sys1yagi/fragment-creator
processor/src/test/assets/TypeSerializerFragment.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // }
import com.sys1yagi.fragmentcreator.ArgsSerializer; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import androidx.fragment.app.Fragment;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class MainFragment extends Fragment { @Args @Serializer(to = String.class, serializer = StringSerializer.class) int id;
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // } // Path: processor/src/test/assets/TypeSerializerFragment.java import com.sys1yagi.fragmentcreator.ArgsSerializer; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import androidx.fragment.app.Fragment; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class MainFragment extends Fragment { @Args @Serializer(to = String.class, serializer = StringSerializer.class) int id;
static class StringSerializer implements ArgsSerializer<Integer, String> {
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/OptionalArgumentsFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/log/Logger.java // public interface Logger extends Parcelable { // // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.log.Logger; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class OptionalArgumentsFragment extends Fragment { @Args(require = false) long id; @Args(require = false) String keyword; @Args(require = false)
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/log/Logger.java // public interface Logger extends Parcelable { // // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/OptionalArgumentsFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.log.Logger; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class OptionalArgumentsFragment extends Fragment { @Args(require = false) long id; @Args(require = false) String keyword; @Args(require = false)
Logger logger;
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/OptionalArgumentsFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/log/Logger.java // public interface Logger extends Parcelable { // // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.log.Logger; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class OptionalArgumentsFragment extends Fragment { @Args(require = false) long id; @Args(require = false) String keyword; @Args(require = false) Logger logger; @Args(require = false)
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/log/Logger.java // public interface Logger extends Parcelable { // // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/OptionalArgumentsFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.log.Logger; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class OptionalArgumentsFragment extends Fragment { @Args(require = false) long id; @Args(require = false) String keyword; @Args(require = false) Logger logger; @Args(require = false)
List<Shop> shops;
sys1yagi/fragment-creator
library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/InvalidParameterException.java // public class InvalidParameterException extends RuntimeException { // // public InvalidParameterException(String message) { // super(message); // } // } // // Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/UnsupportedTypeException.java // public class UnsupportedTypeException extends RuntimeException { // // public UnsupportedTypeException(String message) { // super(message); // } // }
import com.sys1yagi.fragmentcreator.exception.InvalidParameterException; import com.sys1yagi.fragmentcreator.exception.UnsupportedTypeException;
package com.sys1yagi.fragmentcreator; public abstract class FragmentCreator { public static void checkRequire(Object param, String paramName) { if (param == null) {
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/InvalidParameterException.java // public class InvalidParameterException extends RuntimeException { // // public InvalidParameterException(String message) { // super(message); // } // } // // Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/UnsupportedTypeException.java // public class UnsupportedTypeException extends RuntimeException { // // public UnsupportedTypeException(String message) { // super(message); // } // } // Path: library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java import com.sys1yagi.fragmentcreator.exception.InvalidParameterException; import com.sys1yagi.fragmentcreator.exception.UnsupportedTypeException; package com.sys1yagi.fragmentcreator; public abstract class FragmentCreator { public static void checkRequire(Object param, String paramName) { if (param == null) {
throw new UnsupportedTypeException(paramName + " is required.");
sys1yagi/fragment-creator
library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/InvalidParameterException.java // public class InvalidParameterException extends RuntimeException { // // public InvalidParameterException(String message) { // super(message); // } // } // // Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/UnsupportedTypeException.java // public class UnsupportedTypeException extends RuntimeException { // // public UnsupportedTypeException(String message) { // super(message); // } // }
import com.sys1yagi.fragmentcreator.exception.InvalidParameterException; import com.sys1yagi.fragmentcreator.exception.UnsupportedTypeException;
package com.sys1yagi.fragmentcreator; public abstract class FragmentCreator { public static void checkRequire(Object param, String paramName) { if (param == null) { throw new UnsupportedTypeException(paramName + " is required."); } } public static <T> void isValid(T param, Validator<T> validator) { if (!validator.isValid(param)) { //TODO rich message
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/InvalidParameterException.java // public class InvalidParameterException extends RuntimeException { // // public InvalidParameterException(String message) { // super(message); // } // } // // Path: library/src/main/java/com/sys1yagi/fragmentcreator/exception/UnsupportedTypeException.java // public class UnsupportedTypeException extends RuntimeException { // // public UnsupportedTypeException(String message) { // super(message); // } // } // Path: library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java import com.sys1yagi.fragmentcreator.exception.InvalidParameterException; import com.sys1yagi.fragmentcreator.exception.UnsupportedTypeException; package com.sys1yagi.fragmentcreator; public abstract class FragmentCreator { public static void checkRequire(Object param, String paramName) { if (param == null) { throw new UnsupportedTypeException(paramName + " is required."); } } public static <T> void isValid(T param, Validator<T> validator) { if (!validator.isValid(param)) { //TODO rich message
throw new InvalidParameterException(param.getClass().getName() + " is invalid.");
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/MainFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List;
void openFragment(String title) { switch (title) { case REQUIRED_ARGUMENTS: openRequiredArgumentsFragment(); break; case OPTIONAL_ARGUMENTS: openOptionalArgumentsFragment(); break; case NO_ARGUMENTS: openNoArgumentsFragment(); break; case DEFAULT_VALUES: openDefaultValueArgumentsFragment(); break; case TYPE_SERIALIZER: openTypeSerializerFragment(); break; default: Toast.makeText(getContext(), "Not Yet Implemented...", Toast.LENGTH_SHORT).show(); } } void openRequiredArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(REQUIRED_ARGUMENTS) .replace( R.id.container, RequiredArgumentsFragmentCreator
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/MainFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; void openFragment(String title) { switch (title) { case REQUIRED_ARGUMENTS: openRequiredArgumentsFragment(); break; case OPTIONAL_ARGUMENTS: openOptionalArgumentsFragment(); break; case NO_ARGUMENTS: openNoArgumentsFragment(); break; case DEFAULT_VALUES: openDefaultValueArgumentsFragment(); break; case TYPE_SERIALIZER: openTypeSerializerFragment(); break; default: Toast.makeText(getContext(), "Not Yet Implemented...", Toast.LENGTH_SHORT).show(); } } void openRequiredArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(REQUIRED_ARGUMENTS) .replace( R.id.container, RequiredArgumentsFragmentCreator
.newBuilder("Hello Fragment Creator", new Shop(10, "Fragment Creator Store"))
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/MainFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List;
.setShops(shops) .build()) .commit(); } void openNoArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(NO_ARGUMENTS) .replace( R.id.container, NoArgumentsFragmentCreator .newBuilder() .build()) .commit(); } void openDefaultValueArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(DEFAULT_VALUES) .replace( R.id.container, DefaultValueFragmentCreator .newBuilder() .build()) .commit(); } void openTypeSerializerFragment() {
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/MainFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; .setShops(shops) .build()) .commit(); } void openNoArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(NO_ARGUMENTS) .replace( R.id.container, NoArgumentsFragmentCreator .newBuilder() .build()) .commit(); } void openDefaultValueArgumentsFragment() { getFragmentManager() .beginTransaction() .addToBackStack(DEFAULT_VALUES) .replace( R.id.container, DefaultValueFragmentCreator .newBuilder() .build()) .commit(); } void openTypeSerializerFragment() {
Product product = new Product();
sys1yagi/fragment-creator
processor/src/main/java/com/sys1yagi/fragmentcreator/writer/FragmentCreatorWriter.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java // public abstract class FragmentCreator { // // public static void checkRequire(Object param, String paramName) { // if (param == null) { // throw new UnsupportedTypeException(paramName + " is required."); // } // } // // public static <T> void isValid(T param, Validator<T> validator) { // if (!validator.isValid(param)) { // //TODO rich message // throw new InvalidParameterException(param.getClass().getName() + " is invalid."); // } // } // } // // Path: processor/src/main/java/com/sys1yagi/fragmentcreator/model/FragmentCreatorModel.java // public class FragmentCreatorModel { // // private TypeElement element; // // private String packageName; // // private String originalClassName; // // private String creatorClassName; // // private List<VariableElement> argsList = new ArrayList<>(); // // public FragmentCreatorModel(TypeElement element, Elements elementUtils) { // this.element = element; // this.packageName = getPackageName(elementUtils, element); // this.originalClassName = getClassName(element, packageName); // this.creatorClassName = originalClassName.concat("Creator"); // findAnnotations(element); // } // // private void findAnnotations(Element element) { // for (Element enclosedElement : element.getEnclosedElements()) { // findAnnotations(enclosedElement); // // Args args = enclosedElement.getAnnotation(Args.class); // if (args != null) { // this.argsList.add((VariableElement) enclosedElement); // } // } // } // // private String getPackageName(Elements elementUtils, TypeElement type) { // return elementUtils.getPackageOf(type).getQualifiedName().toString(); // } // // private static String getClassName(TypeElement type, String packageName) { // int packageLen = packageName.length() + 1; // return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); // } // // public TypeElement getElement() { // return element; // } // // public String getPackageName() { // return packageName; // } // // public String getOriginalClassName() { // return originalClassName; // } // // public String getCreatorClassName() { // return creatorClassName; // } // // public List<VariableElement> getArgsList() { // return argsList; // } // }
import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import com.sys1yagi.fragmentcreator.FragmentCreator; import com.sys1yagi.fragmentcreator.model.FragmentCreatorModel; import java.io.IOException; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier;
package com.sys1yagi.fragmentcreator.writer; public class FragmentCreatorWriter { FragmentCreatorModel model; ProcessingEnvironment environment; public FragmentCreatorWriter(ProcessingEnvironment environment, FragmentCreatorModel model) { this.environment = environment; this.model = model; } public void write(Filer filer) throws IOException { FragmentCreatorBuilderGenerator fragmentCreatorBuilderGenerator = new FragmentCreatorBuilderGenerator(environment); FragmentCreatorReadGenerator fragmentCreatorReadGenerator = new FragmentCreatorReadGenerator(environment); TypeSpec.Builder classBuilder = createClassBuilder(); classBuilder.addType(fragmentCreatorBuilderGenerator.create(model)); classBuilder.addMethod(fragmentCreatorReadGenerator.createReadMethod(model)); classBuilder.addMethod(fragmentCreatorBuilderGenerator.createBuilderNewBuilder(model, model.getArgsList())); TypeSpec outClass = classBuilder.build(); JavaFile.builder(model.getPackageName(), outClass) .addFileComment("This file was generated by fragment-creator. Do not modify!") .build() .writeTo(filer); } private TypeSpec.Builder createClassBuilder(){ TypeSpec.Builder classBuilder =TypeSpec.classBuilder(model.getCreatorClassName()); classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/FragmentCreator.java // public abstract class FragmentCreator { // // public static void checkRequire(Object param, String paramName) { // if (param == null) { // throw new UnsupportedTypeException(paramName + " is required."); // } // } // // public static <T> void isValid(T param, Validator<T> validator) { // if (!validator.isValid(param)) { // //TODO rich message // throw new InvalidParameterException(param.getClass().getName() + " is invalid."); // } // } // } // // Path: processor/src/main/java/com/sys1yagi/fragmentcreator/model/FragmentCreatorModel.java // public class FragmentCreatorModel { // // private TypeElement element; // // private String packageName; // // private String originalClassName; // // private String creatorClassName; // // private List<VariableElement> argsList = new ArrayList<>(); // // public FragmentCreatorModel(TypeElement element, Elements elementUtils) { // this.element = element; // this.packageName = getPackageName(elementUtils, element); // this.originalClassName = getClassName(element, packageName); // this.creatorClassName = originalClassName.concat("Creator"); // findAnnotations(element); // } // // private void findAnnotations(Element element) { // for (Element enclosedElement : element.getEnclosedElements()) { // findAnnotations(enclosedElement); // // Args args = enclosedElement.getAnnotation(Args.class); // if (args != null) { // this.argsList.add((VariableElement) enclosedElement); // } // } // } // // private String getPackageName(Elements elementUtils, TypeElement type) { // return elementUtils.getPackageOf(type).getQualifiedName().toString(); // } // // private static String getClassName(TypeElement type, String packageName) { // int packageLen = packageName.length() + 1; // return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); // } // // public TypeElement getElement() { // return element; // } // // public String getPackageName() { // return packageName; // } // // public String getOriginalClassName() { // return originalClassName; // } // // public String getCreatorClassName() { // return creatorClassName; // } // // public List<VariableElement> getArgsList() { // return argsList; // } // } // Path: processor/src/main/java/com/sys1yagi/fragmentcreator/writer/FragmentCreatorWriter.java import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import com.sys1yagi.fragmentcreator.FragmentCreator; import com.sys1yagi.fragmentcreator.model.FragmentCreatorModel; import java.io.IOException; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; package com.sys1yagi.fragmentcreator.writer; public class FragmentCreatorWriter { FragmentCreatorModel model; ProcessingEnvironment environment; public FragmentCreatorWriter(ProcessingEnvironment environment, FragmentCreatorModel model) { this.environment = environment; this.model = model; } public void write(Filer filer) throws IOException { FragmentCreatorBuilderGenerator fragmentCreatorBuilderGenerator = new FragmentCreatorBuilderGenerator(environment); FragmentCreatorReadGenerator fragmentCreatorReadGenerator = new FragmentCreatorReadGenerator(environment); TypeSpec.Builder classBuilder = createClassBuilder(); classBuilder.addType(fragmentCreatorBuilderGenerator.create(model)); classBuilder.addMethod(fragmentCreatorReadGenerator.createReadMethod(model)); classBuilder.addMethod(fragmentCreatorBuilderGenerator.createBuilderNewBuilder(model, model.getArgsList())); TypeSpec outClass = classBuilder.build(); JavaFile.builder(model.getPackageName(), outClass) .addFileComment("This file was generated by fragment-creator. Do not modify!") .build() .writeTo(filer); } private TypeSpec.Builder createClassBuilder(){ TypeSpec.Builder classBuilder =TypeSpec.classBuilder(model.getCreatorClassName()); classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
ClassName superClassName = ClassName.get(FragmentCreator.class);
sys1yagi/fragment-creator
processor/src/test/assets/TypeSerializerWithSerializableFragment.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // }
import com.sys1yagi.fragmentcreator.ArgsSerializer; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import java.io.Serializable; import androidx.fragment.app.Fragment;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class MainFragment extends Fragment { @Args @Serializer(to = Holder.class, serializer = SerializableSerializer.class) int id; public static class Holder implements Serializable { int id; public Holder(int id) { this.id = id; } }
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // } // Path: processor/src/test/assets/TypeSerializerWithSerializableFragment.java import com.sys1yagi.fragmentcreator.ArgsSerializer; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import java.io.Serializable; import androidx.fragment.app.Fragment; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class MainFragment extends Fragment { @Args @Serializer(to = Holder.class, serializer = SerializableSerializer.class) int id; public static class Holder implements Serializable { int id; public Holder(int id) { this.id = id; } }
static class SerializableSerializer implements ArgsSerializer<Integer, Holder> {
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/TypeSerializerFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/tool/StringSerializer.java // public class StringSerializer implements ArgsSerializer<Product, String> { // // @Override // public String serialize(Product product) { // return product.getId() + "," + product.getName(); // } // // @Override // public Product deserialize(String str) { // String[] split = str.split(","); // Product product = new Product(); // product.setId(Integer.parseInt(split[0])); // product.setName(split[1]); // return product; // } // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.tool.StringSerializer; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class TypeSerializerFragment extends Fragment { @Args
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/tool/StringSerializer.java // public class StringSerializer implements ArgsSerializer<Product, String> { // // @Override // public String serialize(Product product) { // return product.getId() + "," + product.getName(); // } // // @Override // public Product deserialize(String str) { // String[] split = str.split(","); // Product product = new Product(); // product.setId(Integer.parseInt(split[0])); // product.setName(split[1]); // return product; // } // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/TypeSerializerFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.tool.StringSerializer; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class TypeSerializerFragment extends Fragment { @Args
@Serializer(to = String.class, serializer = StringSerializer.class)
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/TypeSerializerFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/tool/StringSerializer.java // public class StringSerializer implements ArgsSerializer<Product, String> { // // @Override // public String serialize(Product product) { // return product.getId() + "," + product.getName(); // } // // @Override // public Product deserialize(String str) { // String[] split = str.split(","); // Product product = new Product(); // product.setId(Integer.parseInt(split[0])); // product.setName(split[1]); // return product; // } // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.tool.StringSerializer; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class TypeSerializerFragment extends Fragment { @Args @Serializer(to = String.class, serializer = StringSerializer.class)
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Product.java // public class Product { // // public int id; // // public String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/tool/StringSerializer.java // public class StringSerializer implements ArgsSerializer<Product, String> { // // @Override // public String serialize(Product product) { // return product.getId() + "," + product.getName(); // } // // @Override // public Product deserialize(String str) { // String[] split = str.split(","); // Product product = new Product(); // product.setId(Integer.parseInt(split[0])); // product.setName(split[1]); // return product; // } // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/TypeSerializerFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.annotation.Serializer; import com.sys1yagi.fragmentcreator.model.Product; import com.sys1yagi.fragmentcreator.tool.StringSerializer; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class TypeSerializerFragment extends Fragment { @Args @Serializer(to = String.class, serializer = StringSerializer.class)
Product product;
sys1yagi/fragment-creator
sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/RequiredArgumentsFragment.java
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // }
import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class RequiredArgumentsFragment extends Fragment { @Args String keyword; @Args
// Path: sample/src/main/java/com/sys1yagi/fragmentcreator/model/Shop.java // public class Shop implements Parcelable { // // int id; // // String name; // // public Shop(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.id); // dest.writeString(this.name); // } // // public Shop() { // } // // protected Shop(Parcel in) { // this.id = in.readInt(); // this.name = in.readString(); // } // // public static final Parcelable.Creator<Shop> CREATOR = new Parcelable.Creator<Shop>() { // public Shop createFromParcel(Parcel source) { // return new Shop(source); // } // // public Shop[] newArray(int size) { // return new Shop[size]; // } // }; // } // Path: sample/src/main/java/com/sys1yagi/fragmentcreator/fragment/RequiredArgumentsFragment.java import com.sys1yagi.fragmentcreator.R; import com.sys1yagi.fragmentcreator.annotation.Args; import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.model.Shop; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; package com.sys1yagi.fragmentcreator.fragment; @FragmentCreator public class RequiredArgumentsFragment extends Fragment { @Args String keyword; @Args
Shop shop;
sys1yagi/fragment-creator
library/src/main/java/com/sys1yagi/fragmentcreator/annotation/Serializer.java
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // }
import com.sys1yagi.fragmentcreator.ArgsSerializer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package com.sys1yagi.fragmentcreator.annotation; // workaround for kapt // @Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) public @interface Serializer { Class<?> to();
// Path: library/src/main/java/com/sys1yagi/fragmentcreator/ArgsSerializer.java // public interface ArgsSerializer<From, To> { // // To serialize(From from); // // From deserialize(To to); // } // Path: library/src/main/java/com/sys1yagi/fragmentcreator/annotation/Serializer.java import com.sys1yagi.fragmentcreator.ArgsSerializer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package com.sys1yagi.fragmentcreator.annotation; // workaround for kapt // @Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) public @interface Serializer { Class<?> to();
Class<? extends ArgsSerializer> serializer();
sys1yagi/fragment-creator
processor/src/test/java/com/sys1yagi/fragmentcreator/FragmentCreatorProcessorTest.java
// Path: processor/src/test/java/com/sys1yagi/fragmentcreator/testtool/AndroidAwareClassLoader.java // public final class AndroidAwareClassLoader { // // private static final String TEST_CLASSPATH_FILE_NAME = "/additional-test-classpath.txt"; // // private AndroidAwareClassLoader() { // throw new AssertionError(); // } // // public static ClassLoader create() { // try { // InputStream stream = AndroidAwareClassLoader.class.getResourceAsStream(TEST_CLASSPATH_FILE_NAME); // URL[] urls = IOUtils.readLines(stream, Charset.forName("UTF-8")) // .stream() // .map(AndroidAwareClassLoader::unsafeToURL) // .toArray(URL[]::new); // // return new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); // // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // private static URL unsafeToURL(String spec) { // try { // return new URL(spec); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: processor/src/test/java/com/sys1yagi/fragmentcreator/testtool/AssetsUtils.java // public class AssetsUtils { // // public static String readString(String fileName) { // try (FileInputStream fis = new FileInputStream(new File("src/test/assets", fileName))) { // return IOUtils.toString(fis, "UTF-8"); // } catch (IOException e) { // throw new IllegalArgumentException(e); // } // } // }
import com.google.testing.compile.JavaFileObjects; import com.sys1yagi.fragmentcreator.testtool.AndroidAwareClassLoader; import com.sys1yagi.fragmentcreator.testtool.AssetsUtils; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
package com.sys1yagi.fragmentcreator; public class FragmentCreatorProcessorTest { private static final ClassLoader ANDROID_AWARE_CLASSLOADER = AndroidAwareClassLoader.create(); @Test public void illegalTypeException() throws Exception {
// Path: processor/src/test/java/com/sys1yagi/fragmentcreator/testtool/AndroidAwareClassLoader.java // public final class AndroidAwareClassLoader { // // private static final String TEST_CLASSPATH_FILE_NAME = "/additional-test-classpath.txt"; // // private AndroidAwareClassLoader() { // throw new AssertionError(); // } // // public static ClassLoader create() { // try { // InputStream stream = AndroidAwareClassLoader.class.getResourceAsStream(TEST_CLASSPATH_FILE_NAME); // URL[] urls = IOUtils.readLines(stream, Charset.forName("UTF-8")) // .stream() // .map(AndroidAwareClassLoader::unsafeToURL) // .toArray(URL[]::new); // // return new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); // // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // private static URL unsafeToURL(String spec) { // try { // return new URL(spec); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: processor/src/test/java/com/sys1yagi/fragmentcreator/testtool/AssetsUtils.java // public class AssetsUtils { // // public static String readString(String fileName) { // try (FileInputStream fis = new FileInputStream(new File("src/test/assets", fileName))) { // return IOUtils.toString(fis, "UTF-8"); // } catch (IOException e) { // throw new IllegalArgumentException(e); // } // } // } // Path: processor/src/test/java/com/sys1yagi/fragmentcreator/FragmentCreatorProcessorTest.java import com.google.testing.compile.JavaFileObjects; import com.sys1yagi.fragmentcreator.testtool.AndroidAwareClassLoader; import com.sys1yagi.fragmentcreator.testtool.AssetsUtils; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; package com.sys1yagi.fragmentcreator; public class FragmentCreatorProcessorTest { private static final ClassLoader ANDROID_AWARE_CLASSLOADER = AndroidAwareClassLoader.create(); @Test public void illegalTypeException() throws Exception {
String javaFile = AssetsUtils.readString("InvalidMainFragment.java");
sys1yagi/fragment-creator
processor/src/main/java/com/sys1yagi/fragmentcreator/model/EnvParser.java
// Path: processor/src/main/java/com/sys1yagi/fragmentcreator/exception/IllegalTypeException.java // public class IllegalTypeException extends RuntimeException { // // public IllegalTypeException(String message) { // super(message); // } // }
import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.exception.IllegalTypeException; import java.util.ArrayList; import java.util.List; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements;
package com.sys1yagi.fragmentcreator.model; public class EnvParser { public static List<FragmentCreatorModel> parse(RoundEnvironment env, Elements elementUtils) { ArrayList<FragmentCreatorModel> models = new ArrayList<>(); ArrayList<Element> elements = new ArrayList<>( env.getElementsAnnotatedWith(FragmentCreator.class)); for (Element element : elements) { FragmentCreatorModel model = new FragmentCreatorModel((TypeElement) element, elementUtils); models.add(model); } validateFragmentCreatorModel(models); return models; } public static void validateFragmentCreatorModel(List<FragmentCreatorModel> models) { for (FragmentCreatorModel model : models) { TypeMirror superClass = model.getElement().getSuperclass(); BASE_CLASS_CHECK: while (true) { String fqcn = superClass.toString(); switch (fqcn) { case "java.lang.Object":
// Path: processor/src/main/java/com/sys1yagi/fragmentcreator/exception/IllegalTypeException.java // public class IllegalTypeException extends RuntimeException { // // public IllegalTypeException(String message) { // super(message); // } // } // Path: processor/src/main/java/com/sys1yagi/fragmentcreator/model/EnvParser.java import com.sys1yagi.fragmentcreator.annotation.FragmentCreator; import com.sys1yagi.fragmentcreator.exception.IllegalTypeException; import java.util.ArrayList; import java.util.List; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; package com.sys1yagi.fragmentcreator.model; public class EnvParser { public static List<FragmentCreatorModel> parse(RoundEnvironment env, Elements elementUtils) { ArrayList<FragmentCreatorModel> models = new ArrayList<>(); ArrayList<Element> elements = new ArrayList<>( env.getElementsAnnotatedWith(FragmentCreator.class)); for (Element element : elements) { FragmentCreatorModel model = new FragmentCreatorModel((TypeElement) element, elementUtils); models.add(model); } validateFragmentCreatorModel(models); return models; } public static void validateFragmentCreatorModel(List<FragmentCreatorModel> models) { for (FragmentCreatorModel model : models) { TypeMirror superClass = model.getElement().getSuperclass(); BASE_CLASS_CHECK: while (true) { String fqcn = superClass.toString(); switch (fqcn) { case "java.lang.Object":
throw new IllegalTypeException(
jenkinsci/docker-commons-plugin
src/main/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpoint.java
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/impl/ServerHostKeyMaterialFactory.java // @Restricted(NoExternalUse.class) // public class ServerHostKeyMaterialFactory extends KeyMaterialFactory{ // // /** // * The host. // */ // @Nonnull // private final String host; // // public ServerHostKeyMaterialFactory(@Nonnull String host) { // this.host = host; // } // // /** {@inheritDoc} */ // @Override // public KeyMaterial materialize() throws IOException, InterruptedException { // EnvVars env = new EnvVars(); // env.put("DOCKER_HOST", host); // return new KeyMaterialImpl(env); // } // // /** // * Our implementation. // */ // private static class KeyMaterialImpl extends KeyMaterial { // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** {@inheritDoc} */ // private KeyMaterialImpl(EnvVars envVars) { // super(envVars); // } // // /** {@inheritDoc} */ // @Override // public void close() throws IOException { // // } // } // }
import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import hudson.Extension; import hudson.FilePath; import hudson.model.AbstractBuild; import hudson.model.AbstractDescribableImpl; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Item; import hudson.model.Run; import hudson.remoting.VirtualChannel; import hudson.util.ListBoxModel; import jenkins.authentication.tokens.api.AuthenticationTokens; import jenkins.model.Jenkins; import org.jenkinsci.plugins.docker.commons.impl.ServerHostKeyMaterialFactory; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import static hudson.Util.fixEmpty;
/** * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters * needed to access it. */ public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Run context, @Nonnull VirtualChannel target) throws IOException, InterruptedException { DockerServerCredentials creds=null; if (credentialsId!=null) { List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build(); domainRequirements.add(new DockerServerDomainRequirement()); creds = CredentialsProvider.findCredentialById(credentialsId, DockerServerCredentials.class, context, domainRequirements); } // the directory needs to be outside workspace to avoid prying eyes FilePath dotDocker = dotDocker(target); dotDocker.mkdirs(); // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed: return newKeyMaterialFactory(dotDocker, creds); } static FilePath dotDocker(@Nonnull VirtualChannel target) throws IOException, InterruptedException { // TODO this is wrong, should be using WorkspaceList.tempDir return FilePath.getHomeDirectory(target).child(".docker"); } /** * Create a {@link KeyMaterialFactory} for connecting to the docker server/host. */ public KeyMaterialFactory newKeyMaterialFactory(FilePath dir, @Nullable DockerServerCredentials credentials) throws IOException, InterruptedException {
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/impl/ServerHostKeyMaterialFactory.java // @Restricted(NoExternalUse.class) // public class ServerHostKeyMaterialFactory extends KeyMaterialFactory{ // // /** // * The host. // */ // @Nonnull // private final String host; // // public ServerHostKeyMaterialFactory(@Nonnull String host) { // this.host = host; // } // // /** {@inheritDoc} */ // @Override // public KeyMaterial materialize() throws IOException, InterruptedException { // EnvVars env = new EnvVars(); // env.put("DOCKER_HOST", host); // return new KeyMaterialImpl(env); // } // // /** // * Our implementation. // */ // private static class KeyMaterialImpl extends KeyMaterial { // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** {@inheritDoc} */ // private KeyMaterialImpl(EnvVars envVars) { // super(envVars); // } // // /** {@inheritDoc} */ // @Override // public void close() throws IOException { // // } // } // } // Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpoint.java import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import hudson.Extension; import hudson.FilePath; import hudson.model.AbstractBuild; import hudson.model.AbstractDescribableImpl; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Item; import hudson.model.Run; import hudson.remoting.VirtualChannel; import hudson.util.ListBoxModel; import jenkins.authentication.tokens.api.AuthenticationTokens; import jenkins.model.Jenkins; import org.jenkinsci.plugins.docker.commons.impl.ServerHostKeyMaterialFactory; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import static hudson.Util.fixEmpty; /** * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters * needed to access it. */ public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Run context, @Nonnull VirtualChannel target) throws IOException, InterruptedException { DockerServerCredentials creds=null; if (credentialsId!=null) { List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build(); domainRequirements.add(new DockerServerDomainRequirement()); creds = CredentialsProvider.findCredentialById(credentialsId, DockerServerCredentials.class, context, domainRequirements); } // the directory needs to be outside workspace to avoid prying eyes FilePath dotDocker = dotDocker(target); dotDocker.mkdirs(); // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed: return newKeyMaterialFactory(dotDocker, creds); } static FilePath dotDocker(@Nonnull VirtualChannel target) throws IOException, InterruptedException { // TODO this is wrong, should be using WorkspaceList.tempDir return FilePath.getHomeDirectory(target).child(".docker"); } /** * Create a {@link KeyMaterialFactory} for connecting to the docker server/host. */ public KeyMaterialFactory newKeyMaterialFactory(FilePath dir, @Nullable DockerServerCredentials credentials) throws IOException, InterruptedException {
return (uri == null ? KeyMaterialFactory.NULL : new ServerHostKeyMaterialFactory(uri))
jenkinsci/docker-commons-plugin
src/main/java/org/jenkinsci/plugins/docker/commons/impl/ServerHostKeyMaterialFactory.java
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterial.java // public abstract class KeyMaterial implements Closeable, Serializable { // // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** // * {@link KeyMaterial} that does nothing. // */ // public static final KeyMaterial NULL = new NullKeyMaterial(); // // /** // * The environment variables // */ // private final EnvVars envVars; // // protected KeyMaterial(EnvVars envVars) { // this.envVars = envVars; // } // // /** // * Get the environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // */ // public EnvVars env() { // return envVars; // } // // /** // * Deletes the key materials from the file system. As key materials are copied into files // * every time {@link KeyMaterialFactory} is created, it must be also cleaned up each time. // */ // public abstract void close() throws IOException; // // private static final class NullKeyMaterial extends KeyMaterial implements Serializable { // private static final long serialVersionUID = 1L; // protected NullKeyMaterial() { // super(new EnvVars()); // } // @Override // public void close() throws IOException { // } // private Object readResolve() { // return NULL; // } // } // } // // Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterialFactory.java // public abstract class KeyMaterialFactory { // // public static final KeyMaterialFactory NULL = new NullKeyMaterialFactory(); // // private /* write once */ KeyMaterialContext context; // // protected synchronized void checkContextualized() { // if (context == null) { // throw new IllegalStateException("KeyMaterialFactories must be contextualized before use"); // } // } // // /** // * Sets the {@link KeyMaterialContext} within which this {@link KeyMaterialFactory} can {@link #materialize()} // * {@link KeyMaterial} instances. Can only be called once. // * @param context the {@link KeyMaterialContext}. // * @return must return {@code this} (which is only returned to simplify use via method chaining) // */ // public synchronized KeyMaterialFactory contextualize(@Nonnull KeyMaterialContext context) { // if (this.context != null) { // throw new IllegalStateException("KeyMaterialFactories cannot be re-contextualized"); // } // this.context = context; // return this; // } // // @Nonnull // protected synchronized KeyMaterialContext getContext() { // checkContextualized(); // return context; // } // // /** // * Builds the key material environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // * // * <p> // * When you are done using the credentials, call {@link KeyMaterial#close()} to allow sensitive // * information to be removed from the disk. // */ // public abstract KeyMaterial materialize() throws IOException, InterruptedException; // // /** // * Creates a read-protected directory inside {@link KeyMaterialContext#getBaseDir} suitable for storing secret files. // * Be sure to {@link FilePath#deleteRecursive} this in {@link KeyMaterial#close}. // */ // protected final FilePath createSecretsDirectory() throws IOException, InterruptedException { // FilePath dir = new FilePath(getContext().getBaseDir(), UUID.randomUUID().toString()); // dir.mkdirs(); // dir.chmod(0700); // return dir; // } // // /** // * Merge additional {@link KeyMaterialFactory}s into one. // */ // public KeyMaterialFactory plus(@Nullable KeyMaterialFactory... factories) { // if (factories == null || factories.length == 0) { // return this; // } // List<KeyMaterialFactory> tmp = new ArrayList<KeyMaterialFactory>(factories.length + 1); // tmp.add(this); // for (KeyMaterialFactory f: factories) { // if (f != null) tmp.add(f); // } // return new CompositeKeyMaterialFactory(tmp.toArray(new KeyMaterialFactory[tmp.size()])); // } // // }
import java.io.IOException; import hudson.EnvVars; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import javax.annotation.Nonnull;
/* * The MIT License * * Copyright (c) 2015, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.docker.commons.impl; /** * A {@link KeyMaterial} that maintains information about the host. * * @author Stephen Connolly */ @Restricted(NoExternalUse.class) public class ServerHostKeyMaterialFactory extends KeyMaterialFactory{ /** * The host. */ @Nonnull private final String host; public ServerHostKeyMaterialFactory(@Nonnull String host) { this.host = host; } /** {@inheritDoc} */ @Override
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterial.java // public abstract class KeyMaterial implements Closeable, Serializable { // // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** // * {@link KeyMaterial} that does nothing. // */ // public static final KeyMaterial NULL = new NullKeyMaterial(); // // /** // * The environment variables // */ // private final EnvVars envVars; // // protected KeyMaterial(EnvVars envVars) { // this.envVars = envVars; // } // // /** // * Get the environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // */ // public EnvVars env() { // return envVars; // } // // /** // * Deletes the key materials from the file system. As key materials are copied into files // * every time {@link KeyMaterialFactory} is created, it must be also cleaned up each time. // */ // public abstract void close() throws IOException; // // private static final class NullKeyMaterial extends KeyMaterial implements Serializable { // private static final long serialVersionUID = 1L; // protected NullKeyMaterial() { // super(new EnvVars()); // } // @Override // public void close() throws IOException { // } // private Object readResolve() { // return NULL; // } // } // } // // Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterialFactory.java // public abstract class KeyMaterialFactory { // // public static final KeyMaterialFactory NULL = new NullKeyMaterialFactory(); // // private /* write once */ KeyMaterialContext context; // // protected synchronized void checkContextualized() { // if (context == null) { // throw new IllegalStateException("KeyMaterialFactories must be contextualized before use"); // } // } // // /** // * Sets the {@link KeyMaterialContext} within which this {@link KeyMaterialFactory} can {@link #materialize()} // * {@link KeyMaterial} instances. Can only be called once. // * @param context the {@link KeyMaterialContext}. // * @return must return {@code this} (which is only returned to simplify use via method chaining) // */ // public synchronized KeyMaterialFactory contextualize(@Nonnull KeyMaterialContext context) { // if (this.context != null) { // throw new IllegalStateException("KeyMaterialFactories cannot be re-contextualized"); // } // this.context = context; // return this; // } // // @Nonnull // protected synchronized KeyMaterialContext getContext() { // checkContextualized(); // return context; // } // // /** // * Builds the key material environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // * // * <p> // * When you are done using the credentials, call {@link KeyMaterial#close()} to allow sensitive // * information to be removed from the disk. // */ // public abstract KeyMaterial materialize() throws IOException, InterruptedException; // // /** // * Creates a read-protected directory inside {@link KeyMaterialContext#getBaseDir} suitable for storing secret files. // * Be sure to {@link FilePath#deleteRecursive} this in {@link KeyMaterial#close}. // */ // protected final FilePath createSecretsDirectory() throws IOException, InterruptedException { // FilePath dir = new FilePath(getContext().getBaseDir(), UUID.randomUUID().toString()); // dir.mkdirs(); // dir.chmod(0700); // return dir; // } // // /** // * Merge additional {@link KeyMaterialFactory}s into one. // */ // public KeyMaterialFactory plus(@Nullable KeyMaterialFactory... factories) { // if (factories == null || factories.length == 0) { // return this; // } // List<KeyMaterialFactory> tmp = new ArrayList<KeyMaterialFactory>(factories.length + 1); // tmp.add(this); // for (KeyMaterialFactory f: factories) { // if (f != null) tmp.add(f); // } // return new CompositeKeyMaterialFactory(tmp.toArray(new KeyMaterialFactory[tmp.size()])); // } // // } // Path: src/main/java/org/jenkinsci/plugins/docker/commons/impl/ServerHostKeyMaterialFactory.java import java.io.IOException; import hudson.EnvVars; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import javax.annotation.Nonnull; /* * The MIT License * * Copyright (c) 2015, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.docker.commons.impl; /** * A {@link KeyMaterial} that maintains information about the host. * * @author Stephen Connolly */ @Restricted(NoExternalUse.class) public class ServerHostKeyMaterialFactory extends KeyMaterialFactory{ /** * The host. */ @Nonnull private final String host; public ServerHostKeyMaterialFactory(@Nonnull String host) { this.host = host; } /** {@inheritDoc} */ @Override
public KeyMaterial materialize() throws IOException, InterruptedException {
jenkinsci/docker-commons-plugin
src/main/java/org/jenkinsci/plugins/docker/commons/impl/NullKeyMaterialFactory.java
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterial.java // public abstract class KeyMaterial implements Closeable, Serializable { // // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** // * {@link KeyMaterial} that does nothing. // */ // public static final KeyMaterial NULL = new NullKeyMaterial(); // // /** // * The environment variables // */ // private final EnvVars envVars; // // protected KeyMaterial(EnvVars envVars) { // this.envVars = envVars; // } // // /** // * Get the environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // */ // public EnvVars env() { // return envVars; // } // // /** // * Deletes the key materials from the file system. As key materials are copied into files // * every time {@link KeyMaterialFactory} is created, it must be also cleaned up each time. // */ // public abstract void close() throws IOException; // // private static final class NullKeyMaterial extends KeyMaterial implements Serializable { // private static final long serialVersionUID = 1L; // protected NullKeyMaterial() { // super(new EnvVars()); // } // @Override // public void close() throws IOException { // } // private Object readResolve() { // return NULL; // } // } // } // // Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterialFactory.java // public abstract class KeyMaterialFactory { // // public static final KeyMaterialFactory NULL = new NullKeyMaterialFactory(); // // private /* write once */ KeyMaterialContext context; // // protected synchronized void checkContextualized() { // if (context == null) { // throw new IllegalStateException("KeyMaterialFactories must be contextualized before use"); // } // } // // /** // * Sets the {@link KeyMaterialContext} within which this {@link KeyMaterialFactory} can {@link #materialize()} // * {@link KeyMaterial} instances. Can only be called once. // * @param context the {@link KeyMaterialContext}. // * @return must return {@code this} (which is only returned to simplify use via method chaining) // */ // public synchronized KeyMaterialFactory contextualize(@Nonnull KeyMaterialContext context) { // if (this.context != null) { // throw new IllegalStateException("KeyMaterialFactories cannot be re-contextualized"); // } // this.context = context; // return this; // } // // @Nonnull // protected synchronized KeyMaterialContext getContext() { // checkContextualized(); // return context; // } // // /** // * Builds the key material environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // * // * <p> // * When you are done using the credentials, call {@link KeyMaterial#close()} to allow sensitive // * information to be removed from the disk. // */ // public abstract KeyMaterial materialize() throws IOException, InterruptedException; // // /** // * Creates a read-protected directory inside {@link KeyMaterialContext#getBaseDir} suitable for storing secret files. // * Be sure to {@link FilePath#deleteRecursive} this in {@link KeyMaterial#close}. // */ // protected final FilePath createSecretsDirectory() throws IOException, InterruptedException { // FilePath dir = new FilePath(getContext().getBaseDir(), UUID.randomUUID().toString()); // dir.mkdirs(); // dir.chmod(0700); // return dir; // } // // /** // * Merge additional {@link KeyMaterialFactory}s into one. // */ // public KeyMaterialFactory plus(@Nullable KeyMaterialFactory... factories) { // if (factories == null || factories.length == 0) { // return this; // } // List<KeyMaterialFactory> tmp = new ArrayList<KeyMaterialFactory>(factories.length + 1); // tmp.add(this); // for (KeyMaterialFactory f: factories) { // if (f != null) tmp.add(f); // } // return new CompositeKeyMaterialFactory(tmp.toArray(new KeyMaterialFactory[tmp.size()])); // } // // }
import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialContext; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import java.io.IOException;
/* * The MIT License * * Copyright (c) 2015, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.docker.commons.impl; /** * {@link org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory} that does nothing. * * @see org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial#NULL * @author Kohsuke Kawaguchi */ @Restricted(NoExternalUse.class) public final class NullKeyMaterialFactory extends KeyMaterialFactory { @Override
// Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterial.java // public abstract class KeyMaterial implements Closeable, Serializable { // // /** // * Standardize serialization // */ // private static final long serialVersionUID = 1L; // // /** // * {@link KeyMaterial} that does nothing. // */ // public static final KeyMaterial NULL = new NullKeyMaterial(); // // /** // * The environment variables // */ // private final EnvVars envVars; // // protected KeyMaterial(EnvVars envVars) { // this.envVars = envVars; // } // // /** // * Get the environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // */ // public EnvVars env() { // return envVars; // } // // /** // * Deletes the key materials from the file system. As key materials are copied into files // * every time {@link KeyMaterialFactory} is created, it must be also cleaned up each time. // */ // public abstract void close() throws IOException; // // private static final class NullKeyMaterial extends KeyMaterial implements Serializable { // private static final long serialVersionUID = 1L; // protected NullKeyMaterial() { // super(new EnvVars()); // } // @Override // public void close() throws IOException { // } // private Object readResolve() { // return NULL; // } // } // } // // Path: src/main/java/org/jenkinsci/plugins/docker/commons/credentials/KeyMaterialFactory.java // public abstract class KeyMaterialFactory { // // public static final KeyMaterialFactory NULL = new NullKeyMaterialFactory(); // // private /* write once */ KeyMaterialContext context; // // protected synchronized void checkContextualized() { // if (context == null) { // throw new IllegalStateException("KeyMaterialFactories must be contextualized before use"); // } // } // // /** // * Sets the {@link KeyMaterialContext} within which this {@link KeyMaterialFactory} can {@link #materialize()} // * {@link KeyMaterial} instances. Can only be called once. // * @param context the {@link KeyMaterialContext}. // * @return must return {@code this} (which is only returned to simplify use via method chaining) // */ // public synchronized KeyMaterialFactory contextualize(@Nonnull KeyMaterialContext context) { // if (this.context != null) { // throw new IllegalStateException("KeyMaterialFactories cannot be re-contextualized"); // } // this.context = context; // return this; // } // // @Nonnull // protected synchronized KeyMaterialContext getContext() { // checkContextualized(); // return context; // } // // /** // * Builds the key material environment variables needed to be passed when docker runs, to access // * {@link DockerServerCredentials} that this object was created from. // * // * <p> // * When you are done using the credentials, call {@link KeyMaterial#close()} to allow sensitive // * information to be removed from the disk. // */ // public abstract KeyMaterial materialize() throws IOException, InterruptedException; // // /** // * Creates a read-protected directory inside {@link KeyMaterialContext#getBaseDir} suitable for storing secret files. // * Be sure to {@link FilePath#deleteRecursive} this in {@link KeyMaterial#close}. // */ // protected final FilePath createSecretsDirectory() throws IOException, InterruptedException { // FilePath dir = new FilePath(getContext().getBaseDir(), UUID.randomUUID().toString()); // dir.mkdirs(); // dir.chmod(0700); // return dir; // } // // /** // * Merge additional {@link KeyMaterialFactory}s into one. // */ // public KeyMaterialFactory plus(@Nullable KeyMaterialFactory... factories) { // if (factories == null || factories.length == 0) { // return this; // } // List<KeyMaterialFactory> tmp = new ArrayList<KeyMaterialFactory>(factories.length + 1); // tmp.add(this); // for (KeyMaterialFactory f: factories) { // if (f != null) tmp.add(f); // } // return new CompositeKeyMaterialFactory(tmp.toArray(new KeyMaterialFactory[tmp.size()])); // } // // } // Path: src/main/java/org/jenkinsci/plugins/docker/commons/impl/NullKeyMaterialFactory.java import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialContext; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import java.io.IOException; /* * The MIT License * * Copyright (c) 2015, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.docker.commons.impl; /** * {@link org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory} that does nothing. * * @see org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial#NULL * @author Kohsuke Kawaguchi */ @Restricted(NoExternalUse.class) public final class NullKeyMaterialFactory extends KeyMaterialFactory { @Override
public KeyMaterial materialize() throws IOException, InterruptedException {
TORU0239/ViperUsage
app/src/main/java/toru/io/my/viperusage/view/ui/InitViewAdapter.java
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramItemModel.java // public class InstagramItemModel { // private String id; // private String code; // // private UserModel user; // // private ImageModel images; // // @SerializedName("created_time") // private long createdTime; // // @SerializedName("caption") // private CaptionModel caption; // // @SerializedName("user_has_liked") // private boolean HasUserLiked; // // @SerializedName("likes") // private LikeModel likes; // // @SerializedName("comments") // private CommentModel comments; // // @SerializedName("can_view_comments") // private boolean canViewComments; // // @SerializedName("can_delete_comments") // private boolean canDeleteComments; // // private String type; // private String link; // // private LocationModel location; // // @SerializedName("alt_media_url") // private String altMediaUrl; // // @SerializedName("carousel_media") // private List<CarouselModel> carouselMedia; // // @SerializedName("videos") // private VideoModel video; // // @SerializedName("video_views") // private int videoViewsCount; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public UserModel getUser() { // return user; // } // // public void setUser(UserModel user) { // this.user = user; // } // // public ImageModel getImages() { // return images; // } // // public void setImages(ImageModel images) { // this.images = images; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public CaptionModel getCaption() { // return caption; // } // // public void setCaption(CaptionModel caption) { // this.caption = caption; // } // // public boolean isHasUserLiked() { // return HasUserLiked; // } // // public void setHasUserLiked(boolean hasUserLiked) { // HasUserLiked = hasUserLiked; // } // // public LikeModel getLikes() { // return likes; // } // // public void setLikes(LikeModel likes) { // this.likes = likes; // } // // public CommentModel getComments() { // return comments; // } // // public void setComments(CommentModel comments) { // this.comments = comments; // } // // public boolean isCanViewComments() { // return canViewComments; // } // // public void setCanViewComments(boolean canViewComments) { // this.canViewComments = canViewComments; // } // // public boolean isCanDeleteComments() { // return canDeleteComments; // } // // public void setCanDeleteComments(boolean canDeleteComments) { // this.canDeleteComments = canDeleteComments; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getLink() { // return link; // } // // public void setLink(String link) { // this.link = link; // } // // public LocationModel getLocation() { // return location; // } // // public void setLocation(LocationModel location) { // this.location = location; // } // // public String getAltMediaUrl() { // return altMediaUrl; // } // // public void setAltMediaUrl(String altMediaUrl) { // this.altMediaUrl = altMediaUrl; // } // // public List<CarouselModel> getCarouselMedia() { // return carouselMedia; // } // // public void setCarouselMedia(List<CarouselModel> carouselMedia) { // this.carouselMedia = carouselMedia; // } // // public VideoModel getVideo() { // return video; // } // // public void setVideo(VideoModel video) { // this.video = video; // } // // public int getVideoViewsCount() { // return videoViewsCount; // } // // public void setVideoViewsCount(int videoViewsCount) { // this.videoViewsCount = videoViewsCount; // } // }
import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.bumptech.glide.request.target.Target; import java.util.List; import toru.io.my.viperusage.R; import toru.io.my.viperusage.databinding.AdapterInitBinding; import toru.io.my.viperusage.model.InstagramItemModel; import toru.io.my.viperusage.network.GlideApp;
package toru.io.my.viperusage.view.ui; /** * Created by toruchoi on 08/10/2017. */ public class InitViewAdapter extends RecyclerView.Adapter<InitViewAdapter.InitViewHolder> { private static final String TAG = InitViewAdapter.class.getSimpleName();
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramItemModel.java // public class InstagramItemModel { // private String id; // private String code; // // private UserModel user; // // private ImageModel images; // // @SerializedName("created_time") // private long createdTime; // // @SerializedName("caption") // private CaptionModel caption; // // @SerializedName("user_has_liked") // private boolean HasUserLiked; // // @SerializedName("likes") // private LikeModel likes; // // @SerializedName("comments") // private CommentModel comments; // // @SerializedName("can_view_comments") // private boolean canViewComments; // // @SerializedName("can_delete_comments") // private boolean canDeleteComments; // // private String type; // private String link; // // private LocationModel location; // // @SerializedName("alt_media_url") // private String altMediaUrl; // // @SerializedName("carousel_media") // private List<CarouselModel> carouselMedia; // // @SerializedName("videos") // private VideoModel video; // // @SerializedName("video_views") // private int videoViewsCount; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public UserModel getUser() { // return user; // } // // public void setUser(UserModel user) { // this.user = user; // } // // public ImageModel getImages() { // return images; // } // // public void setImages(ImageModel images) { // this.images = images; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public CaptionModel getCaption() { // return caption; // } // // public void setCaption(CaptionModel caption) { // this.caption = caption; // } // // public boolean isHasUserLiked() { // return HasUserLiked; // } // // public void setHasUserLiked(boolean hasUserLiked) { // HasUserLiked = hasUserLiked; // } // // public LikeModel getLikes() { // return likes; // } // // public void setLikes(LikeModel likes) { // this.likes = likes; // } // // public CommentModel getComments() { // return comments; // } // // public void setComments(CommentModel comments) { // this.comments = comments; // } // // public boolean isCanViewComments() { // return canViewComments; // } // // public void setCanViewComments(boolean canViewComments) { // this.canViewComments = canViewComments; // } // // public boolean isCanDeleteComments() { // return canDeleteComments; // } // // public void setCanDeleteComments(boolean canDeleteComments) { // this.canDeleteComments = canDeleteComments; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getLink() { // return link; // } // // public void setLink(String link) { // this.link = link; // } // // public LocationModel getLocation() { // return location; // } // // public void setLocation(LocationModel location) { // this.location = location; // } // // public String getAltMediaUrl() { // return altMediaUrl; // } // // public void setAltMediaUrl(String altMediaUrl) { // this.altMediaUrl = altMediaUrl; // } // // public List<CarouselModel> getCarouselMedia() { // return carouselMedia; // } // // public void setCarouselMedia(List<CarouselModel> carouselMedia) { // this.carouselMedia = carouselMedia; // } // // public VideoModel getVideo() { // return video; // } // // public void setVideo(VideoModel video) { // this.video = video; // } // // public int getVideoViewsCount() { // return videoViewsCount; // } // // public void setVideoViewsCount(int videoViewsCount) { // this.videoViewsCount = videoViewsCount; // } // } // Path: app/src/main/java/toru/io/my/viperusage/view/ui/InitViewAdapter.java import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.bumptech.glide.request.target.Target; import java.util.List; import toru.io.my.viperusage.R; import toru.io.my.viperusage.databinding.AdapterInitBinding; import toru.io.my.viperusage.model.InstagramItemModel; import toru.io.my.viperusage.network.GlideApp; package toru.io.my.viperusage.view.ui; /** * Created by toruchoi on 08/10/2017. */ public class InitViewAdapter extends RecyclerView.Adapter<InitViewAdapter.InitViewHolder> { private static final String TAG = InitViewAdapter.class.getSimpleName();
private List<InstagramItemModel> modelList;
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/api/ApiModule.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // }
import java.util.concurrent.TimeUnit; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import my.liewjuntung.daggerviperusage.network.services.IServices; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(5000, TimeUnit.MILLISECONDS) .writeTimeout(5000, TimeUnit.MILLISECONDS) .addInterceptor(loggingInterceptor) .build(); } @Singleton @Provides public Retrofit.Builder providesRetrofitBuilder(OkHttpClient client) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); } @Singleton @Provides @Named("instagram") public Retrofit providesInstagramRetrofit(Retrofit.Builder builder) { return builder .baseUrl("https://www.instagram.com/") .build(); } @Singleton @Provides
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/api/ApiModule.java import java.util.concurrent.TimeUnit; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import my.liewjuntung.daggerviperusage.network.services.IServices; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(5000, TimeUnit.MILLISECONDS) .writeTimeout(5000, TimeUnit.MILLISECONDS) .addInterceptor(loggingInterceptor) .build(); } @Singleton @Provides public Retrofit.Builder providesRetrofitBuilder(OkHttpClient client) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); } @Singleton @Provides @Named("instagram") public Retrofit providesInstagramRetrofit(Retrofit.Builder builder) { return builder .baseUrl("https://www.instagram.com/") .build(); } @Singleton @Provides
public IServices providesIService(@Named("instagram") Retrofit retrofit) {
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/ActivityBuilder.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitActivity.java // public class InitActivity extends AppCompatActivity implements InitView { // private static final String TAG = InitActivity.class.getSimpleName(); // @Inject // public InitPresenter<RequestModel> presenter; // // not really necessary to inject so many, just to demonstrate that it can be done like this. // // Just for lulz // @Inject // public InitViewAdapter adapter; // @Inject // public LinearLayoutManager layoutManager; // @Inject @Named("kevin") // public RequestModel model; // // // // @Override // protected void onCreate(Bundle savedInstanceState) { // /* Inject this activity, the inject fields are initialized in this point */ // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_init); // // put AndroidInjection.inject(this); here if you want to inject ActivityInitBinding too. // ActivityInitBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_init); // presenter.onCreate(); // // binding.initRecyclerview.setAdapter(adapter); // binding.initRecyclerview.setLayoutManager(layoutManager); // // presenter.onUpdateStart(model); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onPause(); // } // // @Override // protected void onDestroy() { // presenter.onDestroy(); // presenter = null; // super.onDestroy(); // } // // @Override // public void onUpdate(List<InstagramItemModel> result) { // Log.w(TAG, "onUpdate, list size : " + result.size()); // adapter.setModelList(result); // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitModule.java // @Module // public class InitModule { // @Provides // public InitView providesInitActivity(InitActivity initActivity){ // return initActivity; // } // // @Provides // public InitInteractor providesInitInteractor(IServices iServices){ // return new InitInteractorImp(iServices); // } // // @Provides // public InitPresenter<RequestModel> providesInitPresenter(InitView initView, InitInteractor initInteractor){ // return new InitPresenterImp(initView, initInteractor); // } // // @Provides // public InitViewAdapter providesInitViewAdapter(){ // return new InitViewAdapter(); // } // // @Provides // public LinearLayoutManager providesLinearLayoutManager(InitActivity activity){ // return new LinearLayoutManager(activity); // } // // @Provides // @Named("toru") // public RequestModel providesToruRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "toru_0239"; // model.maxId = "0"; // return model; // } // // @Provides // @Named("kevin") // public RequestModel providesJTRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "s1lv3rd3m0n"; // model.maxId = "0"; // return model; // } // // @Provides // public ActivityInitBinding providesActivityBinding(InitActivity activity){ // return DataBindingUtil.setContentView(activity, R.layout.activity_init); // } // }
import dagger.Module; import dagger.android.ContributesAndroidInjector; import my.liewjuntung.daggerviperusage.view.InitActivity; import my.liewjuntung.daggerviperusage.view.InitModule;
package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Module public abstract class ActivityBuilder {
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitActivity.java // public class InitActivity extends AppCompatActivity implements InitView { // private static final String TAG = InitActivity.class.getSimpleName(); // @Inject // public InitPresenter<RequestModel> presenter; // // not really necessary to inject so many, just to demonstrate that it can be done like this. // // Just for lulz // @Inject // public InitViewAdapter adapter; // @Inject // public LinearLayoutManager layoutManager; // @Inject @Named("kevin") // public RequestModel model; // // // // @Override // protected void onCreate(Bundle savedInstanceState) { // /* Inject this activity, the inject fields are initialized in this point */ // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_init); // // put AndroidInjection.inject(this); here if you want to inject ActivityInitBinding too. // ActivityInitBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_init); // presenter.onCreate(); // // binding.initRecyclerview.setAdapter(adapter); // binding.initRecyclerview.setLayoutManager(layoutManager); // // presenter.onUpdateStart(model); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onPause(); // } // // @Override // protected void onDestroy() { // presenter.onDestroy(); // presenter = null; // super.onDestroy(); // } // // @Override // public void onUpdate(List<InstagramItemModel> result) { // Log.w(TAG, "onUpdate, list size : " + result.size()); // adapter.setModelList(result); // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitModule.java // @Module // public class InitModule { // @Provides // public InitView providesInitActivity(InitActivity initActivity){ // return initActivity; // } // // @Provides // public InitInteractor providesInitInteractor(IServices iServices){ // return new InitInteractorImp(iServices); // } // // @Provides // public InitPresenter<RequestModel> providesInitPresenter(InitView initView, InitInteractor initInteractor){ // return new InitPresenterImp(initView, initInteractor); // } // // @Provides // public InitViewAdapter providesInitViewAdapter(){ // return new InitViewAdapter(); // } // // @Provides // public LinearLayoutManager providesLinearLayoutManager(InitActivity activity){ // return new LinearLayoutManager(activity); // } // // @Provides // @Named("toru") // public RequestModel providesToruRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "toru_0239"; // model.maxId = "0"; // return model; // } // // @Provides // @Named("kevin") // public RequestModel providesJTRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "s1lv3rd3m0n"; // model.maxId = "0"; // return model; // } // // @Provides // public ActivityInitBinding providesActivityBinding(InitActivity activity){ // return DataBindingUtil.setContentView(activity, R.layout.activity_init); // } // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/ActivityBuilder.java import dagger.Module; import dagger.android.ContributesAndroidInjector; import my.liewjuntung.daggerviperusage.view.InitActivity; import my.liewjuntung.daggerviperusage.view.InitModule; package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Module public abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = {InitModule.class})
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/ActivityBuilder.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitActivity.java // public class InitActivity extends AppCompatActivity implements InitView { // private static final String TAG = InitActivity.class.getSimpleName(); // @Inject // public InitPresenter<RequestModel> presenter; // // not really necessary to inject so many, just to demonstrate that it can be done like this. // // Just for lulz // @Inject // public InitViewAdapter adapter; // @Inject // public LinearLayoutManager layoutManager; // @Inject @Named("kevin") // public RequestModel model; // // // // @Override // protected void onCreate(Bundle savedInstanceState) { // /* Inject this activity, the inject fields are initialized in this point */ // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_init); // // put AndroidInjection.inject(this); here if you want to inject ActivityInitBinding too. // ActivityInitBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_init); // presenter.onCreate(); // // binding.initRecyclerview.setAdapter(adapter); // binding.initRecyclerview.setLayoutManager(layoutManager); // // presenter.onUpdateStart(model); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onPause(); // } // // @Override // protected void onDestroy() { // presenter.onDestroy(); // presenter = null; // super.onDestroy(); // } // // @Override // public void onUpdate(List<InstagramItemModel> result) { // Log.w(TAG, "onUpdate, list size : " + result.size()); // adapter.setModelList(result); // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitModule.java // @Module // public class InitModule { // @Provides // public InitView providesInitActivity(InitActivity initActivity){ // return initActivity; // } // // @Provides // public InitInteractor providesInitInteractor(IServices iServices){ // return new InitInteractorImp(iServices); // } // // @Provides // public InitPresenter<RequestModel> providesInitPresenter(InitView initView, InitInteractor initInteractor){ // return new InitPresenterImp(initView, initInteractor); // } // // @Provides // public InitViewAdapter providesInitViewAdapter(){ // return new InitViewAdapter(); // } // // @Provides // public LinearLayoutManager providesLinearLayoutManager(InitActivity activity){ // return new LinearLayoutManager(activity); // } // // @Provides // @Named("toru") // public RequestModel providesToruRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "toru_0239"; // model.maxId = "0"; // return model; // } // // @Provides // @Named("kevin") // public RequestModel providesJTRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "s1lv3rd3m0n"; // model.maxId = "0"; // return model; // } // // @Provides // public ActivityInitBinding providesActivityBinding(InitActivity activity){ // return DataBindingUtil.setContentView(activity, R.layout.activity_init); // } // }
import dagger.Module; import dagger.android.ContributesAndroidInjector; import my.liewjuntung.daggerviperusage.view.InitActivity; import my.liewjuntung.daggerviperusage.view.InitModule;
package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Module public abstract class ActivityBuilder { @ContributesAndroidInjector(modules = {InitModule.class})
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitActivity.java // public class InitActivity extends AppCompatActivity implements InitView { // private static final String TAG = InitActivity.class.getSimpleName(); // @Inject // public InitPresenter<RequestModel> presenter; // // not really necessary to inject so many, just to demonstrate that it can be done like this. // // Just for lulz // @Inject // public InitViewAdapter adapter; // @Inject // public LinearLayoutManager layoutManager; // @Inject @Named("kevin") // public RequestModel model; // // // // @Override // protected void onCreate(Bundle savedInstanceState) { // /* Inject this activity, the inject fields are initialized in this point */ // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_init); // // put AndroidInjection.inject(this); here if you want to inject ActivityInitBinding too. // ActivityInitBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_init); // presenter.onCreate(); // // binding.initRecyclerview.setAdapter(adapter); // binding.initRecyclerview.setLayoutManager(layoutManager); // // presenter.onUpdateStart(model); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onPause(); // } // // @Override // protected void onDestroy() { // presenter.onDestroy(); // presenter = null; // super.onDestroy(); // } // // @Override // public void onUpdate(List<InstagramItemModel> result) { // Log.w(TAG, "onUpdate, list size : " + result.size()); // adapter.setModelList(result); // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/InitModule.java // @Module // public class InitModule { // @Provides // public InitView providesInitActivity(InitActivity initActivity){ // return initActivity; // } // // @Provides // public InitInteractor providesInitInteractor(IServices iServices){ // return new InitInteractorImp(iServices); // } // // @Provides // public InitPresenter<RequestModel> providesInitPresenter(InitView initView, InitInteractor initInteractor){ // return new InitPresenterImp(initView, initInteractor); // } // // @Provides // public InitViewAdapter providesInitViewAdapter(){ // return new InitViewAdapter(); // } // // @Provides // public LinearLayoutManager providesLinearLayoutManager(InitActivity activity){ // return new LinearLayoutManager(activity); // } // // @Provides // @Named("toru") // public RequestModel providesToruRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "toru_0239"; // model.maxId = "0"; // return model; // } // // @Provides // @Named("kevin") // public RequestModel providesJTRequestModel(){ // RequestModel model = new RequestModel(); // model.id = "s1lv3rd3m0n"; // model.maxId = "0"; // return model; // } // // @Provides // public ActivityInitBinding providesActivityBinding(InitActivity activity){ // return DataBindingUtil.setContentView(activity, R.layout.activity_init); // } // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/ActivityBuilder.java import dagger.Module; import dagger.android.ContributesAndroidInjector; import my.liewjuntung.daggerviperusage.view.InitActivity; import my.liewjuntung.daggerviperusage.view.InitModule; package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Module public abstract class ActivityBuilder { @ContributesAndroidInjector(modules = {InitModule.class})
public abstract InitActivity bindInitActivity();
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // }
import io.reactivex.Observable; import my.liewjuntung.daggerviperusage.model.InstagramResponse; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query;
package my.liewjuntung.daggerviperusage.network.services; /** * Created by toruchoi on 08/10/2017. */ public interface IServices { @GET("{filter}/media/")
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java import io.reactivex.Observable; import my.liewjuntung.daggerviperusage.model.InstagramResponse; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; package my.liewjuntung.daggerviperusage.network.services; /** * Created by toruchoi on 08/10/2017. */ public interface IServices { @GET("{filter}/media/")
Observable<InstagramResponse> getService(@Path("filter") String filter,
TORU0239/ViperUsage
app/src/main/java/toru/io/my/viperusage/network/services/IServices.java
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // }
import org.json.JSONObject; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import toru.io.my.viperusage.model.InstagramResponse;
package toru.io.my.viperusage.network.services; /** * Created by toruchoi on 08/10/2017. */ public interface IServices { @GET("{filter}/media/")
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java import org.json.JSONObject; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import toru.io.my.viperusage.model.InstagramResponse; package toru.io.my.viperusage.network.services; /** * Created by toruchoi on 08/10/2017. */ public interface IServices { @GET("{filter}/media/")
Observable<InstagramResponse> getService(@Path("filter") String filter,
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/ui/InitViewAdapter.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/model/InstagramItemModel.java // public class InstagramItemModel { // private String id; // private String code; // // private UserModel user; // // private ImageModel images; // // @SerializedName("created_time") // private long createdTime; // // @SerializedName("caption") // private CaptionModel caption; // // @SerializedName("user_has_liked") // private boolean HasUserLiked; // // @SerializedName("likes") // private LikeModel likes; // // @SerializedName("comments") // private CommentModel comments; // // @SerializedName("can_view_comments") // private boolean canViewComments; // // @SerializedName("can_delete_comments") // private boolean canDeleteComments; // // private String type; // private String link; // // private LocationModel location; // // @SerializedName("alt_media_url") // private String altMediaUrl; // // @SerializedName("carousel_media") // private List<CarouselModel> carouselMedia; // // @SerializedName("videos") // private VideoModel video; // // @SerializedName("video_views") // private int videoViewsCount; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public UserModel getUser() { // return user; // } // // public void setUser(UserModel user) { // this.user = user; // } // // public ImageModel getImages() { // return images; // } // // public void setImages(ImageModel images) { // this.images = images; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public CaptionModel getCaption() { // return caption; // } // // public void setCaption(CaptionModel caption) { // this.caption = caption; // } // // public boolean isHasUserLiked() { // return HasUserLiked; // } // // public void setHasUserLiked(boolean hasUserLiked) { // HasUserLiked = hasUserLiked; // } // // public LikeModel getLikes() { // return likes; // } // // public void setLikes(LikeModel likes) { // this.likes = likes; // } // // public CommentModel getComments() { // return comments; // } // // public void setComments(CommentModel comments) { // this.comments = comments; // } // // public boolean isCanViewComments() { // return canViewComments; // } // // public void setCanViewComments(boolean canViewComments) { // this.canViewComments = canViewComments; // } // // public boolean isCanDeleteComments() { // return canDeleteComments; // } // // public void setCanDeleteComments(boolean canDeleteComments) { // this.canDeleteComments = canDeleteComments; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getLink() { // return link; // } // // public void setLink(String link) { // this.link = link; // } // // public LocationModel getLocation() { // return location; // } // // public void setLocation(LocationModel location) { // this.location = location; // } // // public String getAltMediaUrl() { // return altMediaUrl; // } // // public void setAltMediaUrl(String altMediaUrl) { // this.altMediaUrl = altMediaUrl; // } // // public List<CarouselModel> getCarouselMedia() { // return carouselMedia; // } // // public void setCarouselMedia(List<CarouselModel> carouselMedia) { // this.carouselMedia = carouselMedia; // } // // public VideoModel getVideo() { // return video; // } // // public void setVideo(VideoModel video) { // this.video = video; // } // // public int getVideoViewsCount() { // return videoViewsCount; // } // // public void setVideoViewsCount(int videoViewsCount) { // this.videoViewsCount = videoViewsCount; // } // }
import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.bumptech.glide.request.target.Target; import java.util.List; import my.liewjuntung.daggerviperusage.R; import my.liewjuntung.daggerviperusage.databinding.AdapterInitBinding; import my.liewjuntung.daggerviperusage.model.InstagramItemModel; import my.liewjuntung.daggerviperusage.network.GlideApp;
package my.liewjuntung.daggerviperusage.view.ui; /** * Created by toruchoi on 08/10/2017. */ public class InitViewAdapter extends RecyclerView.Adapter<InitViewAdapter.InitViewHolder> { private static final String TAG = InitViewAdapter.class.getSimpleName();
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/model/InstagramItemModel.java // public class InstagramItemModel { // private String id; // private String code; // // private UserModel user; // // private ImageModel images; // // @SerializedName("created_time") // private long createdTime; // // @SerializedName("caption") // private CaptionModel caption; // // @SerializedName("user_has_liked") // private boolean HasUserLiked; // // @SerializedName("likes") // private LikeModel likes; // // @SerializedName("comments") // private CommentModel comments; // // @SerializedName("can_view_comments") // private boolean canViewComments; // // @SerializedName("can_delete_comments") // private boolean canDeleteComments; // // private String type; // private String link; // // private LocationModel location; // // @SerializedName("alt_media_url") // private String altMediaUrl; // // @SerializedName("carousel_media") // private List<CarouselModel> carouselMedia; // // @SerializedName("videos") // private VideoModel video; // // @SerializedName("video_views") // private int videoViewsCount; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public UserModel getUser() { // return user; // } // // public void setUser(UserModel user) { // this.user = user; // } // // public ImageModel getImages() { // return images; // } // // public void setImages(ImageModel images) { // this.images = images; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public CaptionModel getCaption() { // return caption; // } // // public void setCaption(CaptionModel caption) { // this.caption = caption; // } // // public boolean isHasUserLiked() { // return HasUserLiked; // } // // public void setHasUserLiked(boolean hasUserLiked) { // HasUserLiked = hasUserLiked; // } // // public LikeModel getLikes() { // return likes; // } // // public void setLikes(LikeModel likes) { // this.likes = likes; // } // // public CommentModel getComments() { // return comments; // } // // public void setComments(CommentModel comments) { // this.comments = comments; // } // // public boolean isCanViewComments() { // return canViewComments; // } // // public void setCanViewComments(boolean canViewComments) { // this.canViewComments = canViewComments; // } // // public boolean isCanDeleteComments() { // return canDeleteComments; // } // // public void setCanDeleteComments(boolean canDeleteComments) { // this.canDeleteComments = canDeleteComments; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getLink() { // return link; // } // // public void setLink(String link) { // this.link = link; // } // // public LocationModel getLocation() { // return location; // } // // public void setLocation(LocationModel location) { // this.location = location; // } // // public String getAltMediaUrl() { // return altMediaUrl; // } // // public void setAltMediaUrl(String altMediaUrl) { // this.altMediaUrl = altMediaUrl; // } // // public List<CarouselModel> getCarouselMedia() { // return carouselMedia; // } // // public void setCarouselMedia(List<CarouselModel> carouselMedia) { // this.carouselMedia = carouselMedia; // } // // public VideoModel getVideo() { // return video; // } // // public void setVideo(VideoModel video) { // this.video = video; // } // // public int getVideoViewsCount() { // return videoViewsCount; // } // // public void setVideoViewsCount(int videoViewsCount) { // this.videoViewsCount = videoViewsCount; // } // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/view/ui/InitViewAdapter.java import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.bumptech.glide.request.target.Target; import java.util.List; import my.liewjuntung.daggerviperusage.R; import my.liewjuntung.daggerviperusage.databinding.AdapterInitBinding; import my.liewjuntung.daggerviperusage.model.InstagramItemModel; import my.liewjuntung.daggerviperusage.network.GlideApp; package my.liewjuntung.daggerviperusage.view.ui; /** * Created by toruchoi on 08/10/2017. */ public class InitViewAdapter extends RecyclerView.Adapter<InitViewAdapter.InitViewHolder> { private static final String TAG = InitViewAdapter.class.getSimpleName();
private List<InstagramItemModel> modelList;
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // }
import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut;
package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName();
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut; package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName();
private IServices services;
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // }
import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut;
package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private IServices services; @Inject public InitInteractorImp(IServices services) { this.services = services; } @Override
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut; package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private IServices services; @Inject public InitInteractorImp(IServices services) { this.services = services; } @Override
public void onGetResponse(BViperInteractorOut out, RequestModel request) {
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // }
import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut;
package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private IServices services; @Inject public InitInteractorImp(IServices services) { this.services = services; } @Override
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // // Path: bviper/src/main/java/toru/io/my/bviper/interactor/BViperInteractorOut.java // public interface BViperInteractorOut<T> { // void onResponseSuccess(T result); // void onResponseFailed(Throwable throwable); // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/interactor/InitInteractorImp.java import android.util.Log; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import my.liewjuntung.daggerviperusage.network.services.IServices; import my.liewjuntung.daggerviperusage.network.services.RequestModel; import toru.io.my.bviper.interactor.BViperInteractorOut; package my.liewjuntung.daggerviperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private IServices services; @Inject public InitInteractorImp(IServices services) { this.services = services; } @Override
public void onGetResponse(BViperInteractorOut out, RequestModel request) {
TORU0239/ViperUsage
dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/AppComponent.java
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/app/ViperUsageApplication.java // public class ViperUsageApplication extends Application implements HasActivityInjector { // private static final String TAG = ViperUsageApplication.class.getSimpleName(); // // @Inject // DispatchingAndroidInjector<Activity> androidInjector; // // @Override // public void onCreate() { // super.onCreate(); // DaggerAppComponent // .builder() // .application(this) // .build() // .inject(this); // } // // @Override // public AndroidInjector<Activity> activityInjector() { // return androidInjector; // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/api/ApiModule.java // @Module // public class ApiModule { // @Singleton // @Provides // public OkHttpClient providesOkHttpClient() { // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // } // // @Singleton // @Provides // public Retrofit.Builder providesRetrofitBuilder(OkHttpClient client) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); // } // // @Singleton // @Provides // @Named("instagram") // public Retrofit providesInstagramRetrofit(Retrofit.Builder builder) { // return builder // .baseUrl("https://www.instagram.com/") // .build(); // } // // @Singleton // @Provides // public IServices providesIService(@Named("instagram") Retrofit retrofit) { // return retrofit.create(IServices.class); // } // }
import android.app.Application; import javax.inject.Singleton; import dagger.BindsInstance; import dagger.Component; import dagger.android.AndroidInjectionModule; import my.liewjuntung.daggerviperusage.app.ViperUsageApplication; import my.liewjuntung.daggerviperusage.dagger.api.ApiModule;
package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Singleton @Component(modules = {AndroidInjectionModule.class, AppModule.class, ActivityBuilder.class, ApiModule.class}) public interface AppComponent { @Component.Builder interface Builder { AppComponent build(); @BindsInstance Builder application(Application application); } /** * Create an interface for {@link my.liewjuntung.daggerviperusage.app.ViperUsageApplication} to be injected */
// Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/app/ViperUsageApplication.java // public class ViperUsageApplication extends Application implements HasActivityInjector { // private static final String TAG = ViperUsageApplication.class.getSimpleName(); // // @Inject // DispatchingAndroidInjector<Activity> androidInjector; // // @Override // public void onCreate() { // super.onCreate(); // DaggerAppComponent // .builder() // .application(this) // .build() // .inject(this); // } // // @Override // public AndroidInjector<Activity> activityInjector() { // return androidInjector; // } // } // // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/api/ApiModule.java // @Module // public class ApiModule { // @Singleton // @Provides // public OkHttpClient providesOkHttpClient() { // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // } // // @Singleton // @Provides // public Retrofit.Builder providesRetrofitBuilder(OkHttpClient client) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); // } // // @Singleton // @Provides // @Named("instagram") // public Retrofit providesInstagramRetrofit(Retrofit.Builder builder) { // return builder // .baseUrl("https://www.instagram.com/") // .build(); // } // // @Singleton // @Provides // public IServices providesIService(@Named("instagram") Retrofit retrofit) { // return retrofit.create(IServices.class); // } // } // Path: dagger_app/src/main/java/my/liewjuntung/daggerviperusage/dagger/AppComponent.java import android.app.Application; import javax.inject.Singleton; import dagger.BindsInstance; import dagger.Component; import dagger.android.AndroidInjectionModule; import my.liewjuntung.daggerviperusage.app.ViperUsageApplication; import my.liewjuntung.daggerviperusage.dagger.api.ApiModule; package my.liewjuntung.daggerviperusage.dagger; /** * Created by pandawarrior on 24/10/2017. */ @Singleton @Component(modules = {AndroidInjectionModule.class, AppModule.class, ActivityBuilder.class, ApiModule.class}) public interface AppComponent { @Component.Builder interface Builder { AppComponent build(); @BindsInstance Builder application(Application application); } /** * Create an interface for {@link my.liewjuntung.daggerviperusage.app.ViperUsageApplication} to be injected */
void inject(ViperUsageApplication application);
TORU0239/ViperUsage
app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // }
import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel;
package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // Path: app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel; package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override
public void onGetResponse(RequestModel request) {
TORU0239/ViperUsage
app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // }
import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel;
package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override public void onGetResponse(RequestModel request) {
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // Path: app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel; package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override public void onGetResponse(RequestModel request) {
Retrofit retrofit = ApiBase.getInstance("https://www.instagram.com/").getRetrofit();
TORU0239/ViperUsage
app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // }
import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel;
package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override public void onGetResponse(RequestModel request) { Retrofit retrofit = ApiBase.getInstance("https://www.instagram.com/").getRetrofit();
// Path: app/src/main/java/toru/io/my/viperusage/model/InstagramResponse.java // public class InstagramResponse { // public List<InstagramItemModel> items; // // @SerializedName("more_available") // public boolean moreAvailable; // // public String status; // } // // Path: app/src/main/java/toru/io/my/viperusage/network/ApiBase.java // public class ApiBase { // private static final String TAG = ApiBase.class.getSimpleName(); // // private static ApiBase instance; // private Retrofit retrofit; // // private ApiBase(String baseUrl){ // initWithBaseUrl(baseUrl); // } // // public static ApiBase getInstance(String baseUrl){ // if(instance == null){ // instance = new ApiBase(baseUrl); // } // return instance; // } // // private void initWithBaseUrl(String baseUrl){ // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(5000, TimeUnit.MILLISECONDS) // .readTimeout(5000, TimeUnit.MILLISECONDS) // .writeTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(loggingInterceptor) // .build(); // // retrofit = new Retrofit.Builder() // .baseUrl(baseUrl) // .addConverterFactory(GsonConverterFactory.create()) // .client(client) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // public Retrofit getRetrofit(){ // return retrofit; // } // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/IServices.java // public interface IServices { // @GET("{filter}/media/") // Observable<InstagramResponse> getService(@Path("filter") String filter, // @Query("max_id") String maxId); // } // // Path: app/src/main/java/toru/io/my/viperusage/network/services/RequestModel.java // public class RequestModel { // public String id; // public String maxId; // } // Path: app/src/main/java/toru/io/my/viperusage/interactor/InitInteractorImp.java import android.util.Log; import org.json.JSONObject; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import toru.io.my.viperusage.model.InstagramResponse; import toru.io.my.viperusage.network.ApiBase; import toru.io.my.viperusage.network.services.IServices; import toru.io.my.viperusage.network.services.RequestModel; package toru.io.my.viperusage.interactor; /** * Created by toruchoi on 06/10/2017. */ public class InitInteractorImp implements InitInteractor{ private static final String TAG = InitInteractorImp.class.getSimpleName(); private InitInteractorOut out; public InitInteractorImp(InitInteractorOut out) { this.out = out; } @Override public void onGetResponse(RequestModel request) { Retrofit retrofit = ApiBase.getInstance("https://www.instagram.com/").getRetrofit();
IServices services = retrofit.create(IServices.class);
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/dexx/DexxValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.dexx; public class DexxValueFactory implements JmhValueFactory { @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/dexx/DexxValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.dexx; public class DexxValueFactory implements JmhValueFactory { @Override
public JmhSet.Builder setBuilder() {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/dexx/DexxValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.dexx; public class DexxValueFactory implements JmhValueFactory { @Override public JmhSet.Builder setBuilder() { return new DexxSetBuilder(); } @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/dexx/DexxValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.dexx; public class DexxValueFactory implements JmhValueFactory { @Override public JmhSet.Builder setBuilder() { return new DexxSetBuilder(); } @Override
public JmhMap.Builder mapBuilder() {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/paguro/PaguroValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.paguro; public class PaguroValueFactory implements JmhValueFactory { @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/paguro/PaguroValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.paguro; public class PaguroValueFactory implements JmhValueFactory { @Override
public JmhSet.Builder setBuilder() {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/paguro/PaguroValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.paguro; public class PaguroValueFactory implements JmhValueFactory { @Override public JmhSet.Builder setBuilder() { return new PaguroSetBuilder(); } @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/paguro/PaguroValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.paguro; public class PaguroValueFactory implements JmhValueFactory { @Override public JmhSet.Builder setBuilder() { return new PaguroSetBuilder(); } @Override
public JmhMap.Builder mapBuilder() {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/clojure/ClojureValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSetMultimap.java // public interface JmhSetMultimap extends JmhValue { // Iterable<JmhValue> // // boolean isEmpty(); // // int size(); // // JmhSetMultimap insert(JmhValue key, JmhValue value); // // JmhSetMultimap remove(JmhValue key, JmhValue value); // // JmhSetMultimap put(JmhValue key, JmhValue value); // // JmhSetMultimap remove(JmhValue key); // // boolean containsKey(JmhValue key); // // boolean containsValue(JmhValue value); // // boolean contains(JmhValue key, JmhValue value); // // // JmhValue get(JmhValue key); // // // // boolean containsValue(JmhValue value); // // Iterator<JmhValue> iterator(); // // // Iterator<JmhValue> valueIterator(); // // Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // Iterator<Entry<JmhValue, Object>> nativeEntryIterator(); // // java.util.Set<JmhValue> keySet(); // // public static interface Builder extends JmhBuilder { // // void insert(JmhValue key, JmhValue value); // // // void putAll(JmhMap map); // // // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhSetMultimap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhSetMultimap; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.clojure; public class ClojureValueFactory implements JmhValueFactory { @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSetMultimap.java // public interface JmhSetMultimap extends JmhValue { // Iterable<JmhValue> // // boolean isEmpty(); // // int size(); // // JmhSetMultimap insert(JmhValue key, JmhValue value); // // JmhSetMultimap remove(JmhValue key, JmhValue value); // // JmhSetMultimap put(JmhValue key, JmhValue value); // // JmhSetMultimap remove(JmhValue key); // // boolean containsKey(JmhValue key); // // boolean containsValue(JmhValue value); // // boolean contains(JmhValue key, JmhValue value); // // // JmhValue get(JmhValue key); // // // // boolean containsValue(JmhValue value); // // Iterator<JmhValue> iterator(); // // // Iterator<JmhValue> valueIterator(); // // Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // Iterator<Entry<JmhValue, Object>> nativeEntryIterator(); // // java.util.Set<JmhValue> keySet(); // // public static interface Builder extends JmhBuilder { // // void insert(JmhValue key, JmhValue value); // // // void putAll(JmhMap map); // // // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhSetMultimap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/clojure/ClojureValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhSetMultimap; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.clojure; public class ClojureValueFactory implements JmhValueFactory { @Override
public JmhMap.Builder mapBuilder() {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/FootprintUtils.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className,
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/FootprintUtils.java import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className,
DataType dataType, Archetype archetype, boolean supportsStagedMutability, int size, int run,
msteindorfer/criterion
src/main/java/io/usethesource/criterion/FootprintUtils.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className,
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/FootprintUtils.java import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className,
DataType dataType, Archetype archetype, boolean supportsStagedMutability, int size, int run,
msteindorfer/criterion
src/main/java/io/usethesource/criterion/FootprintUtils.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className, DataType dataType, Archetype archetype, boolean supportsStagedMutability, int size, int run, MemoryFootprintPreset preset) { final Predicate<Object> predicate; switch (preset) { case DATA_STRUCTURE_OVERHEAD:
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public enum Archetype { // MUTABLE, IMMUTABLE, PERSISTENT // } // // Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static enum DataType { // MAP, SET_MULTIMAP, SET // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/FootprintUtils.java import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import io.usethesource.criterion.BenchmarkUtils.Archetype; import io.usethesource.criterion.BenchmarkUtils.DataType; import io.usethesource.criterion.api.JmhValue; import objectexplorer.ObjectGraphMeasurer.Footprint; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public final class FootprintUtils { final static String CSV_HEADER = "elementCount,run,className,dataType,archetype,supportsStagedMutability,footprintInBytes,footprintInObjects,footprintInReferences"; // ,footprintInPrimitives /* * NOTE: with extensions for heterogeneous data */ public enum MemoryFootprintPreset { RETAINED_SIZE, DATA_STRUCTURE_OVERHEAD, RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER } public static String measureAndReport(final Object objectToMeasure, final String className, DataType dataType, Archetype archetype, boolean supportsStagedMutability, int size, int run, MemoryFootprintPreset preset) { final Predicate<Object> predicate; switch (preset) { case DATA_STRUCTURE_OVERHEAD:
predicate = Predicates.not(Predicates.instanceOf(JmhValue.class));
msteindorfer/criterion
src/main/java/io/usethesource/criterion/profiler/CountingIntegerProfiler.java
// Path: src/main/java/io/usethesource/criterion/CountingInteger.java // @CompilerControl(Mode.DONT_INLINE) // public class CountingInteger implements JmhValue { // // private static long HASHCODE_COUNTER = 0; // private static long EQUALS_COUNTER = 0; // // public static void resetCounters() { // HASHCODE_COUNTER = 0; // EQUALS_COUNTER = 0; // } // // public static long getHashcodeCounter() { // return HASHCODE_COUNTER; // } // // public static long getEqualsCounter() { // return EQUALS_COUNTER; // } // // private int value; // // CountingInteger(int value) { // this.value = value; // } // // @Override // public int hashCode() { // HASHCODE_COUNTER++; // return value; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof CountingInteger) { // int otherValue = ((CountingInteger) other).value; // // EQUALS_COUNTER++; // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // }
import java.util.Arrays; import java.util.Collection; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.profile.InternalProfiler; import org.openjdk.jmh.profile.ProfilerResult; import org.openjdk.jmh.results.AggregationPolicy; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import io.usethesource.criterion.CountingInteger;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.profiler; public class CountingIntegerProfiler implements InternalProfiler { @Override public String getDescription() { return "Counts the number of hashCode() and equals() invocations on class 'CountingInteger'"; } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) {
// Path: src/main/java/io/usethesource/criterion/CountingInteger.java // @CompilerControl(Mode.DONT_INLINE) // public class CountingInteger implements JmhValue { // // private static long HASHCODE_COUNTER = 0; // private static long EQUALS_COUNTER = 0; // // public static void resetCounters() { // HASHCODE_COUNTER = 0; // EQUALS_COUNTER = 0; // } // // public static long getHashcodeCounter() { // return HASHCODE_COUNTER; // } // // public static long getEqualsCounter() { // return EQUALS_COUNTER; // } // // private int value; // // CountingInteger(int value) { // this.value = value; // } // // @Override // public int hashCode() { // HASHCODE_COUNTER++; // return value; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof CountingInteger) { // int otherValue = ((CountingInteger) other).value; // // EQUALS_COUNTER++; // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // } // Path: src/main/java/io/usethesource/criterion/profiler/CountingIntegerProfiler.java import java.util.Arrays; import java.util.Collection; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.profile.InternalProfiler; import org.openjdk.jmh.profile.ProfilerResult; import org.openjdk.jmh.results.AggregationPolicy; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import io.usethesource.criterion.CountingInteger; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.profiler; public class CountingIntegerProfiler implements InternalProfiler { @Override public String getDescription() { return "Counts the number of hashCode() and equals() invocations on class 'CountingInteger'"; } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) {
CountingInteger.resetCounters();
msteindorfer/criterion
src/main/java/io/usethesource/criterion/ElementProducer.java
// Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import io.usethesource.criterion.api.JmhValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public enum ElementProducer { PDB_INTEGER { @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/ElementProducer.java import io.usethesource.criterion.api.JmhValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; public enum ElementProducer { PDB_INTEGER { @Override
public JmhValue createFromInt(int value) {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/clojure/ClojureMap.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import java.util.Iterator; import java.util.Map.Entry; import clojure.lang.APersistentMap; import clojure.lang.IPersistentMap; import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.clojure; public class ClojureMap implements JmhMap { protected final IPersistentMap xs; protected ClojureMap(IPersistentMap xs) { this.xs = xs; } @Override public boolean isEmpty() { return size() == 0; } @Override public int size() { return xs.count(); } @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/clojure/ClojureMap.java import java.util.Iterator; import java.util.Map.Entry; import clojure.lang.APersistentMap; import clojure.lang.IPersistentMap; import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.clojure; public class ClojureMap implements JmhMap { protected final IPersistentMap xs; protected ClojureMap(IPersistentMap xs) { this.xs = xs; } @Override public boolean isEmpty() { return size() == 0; } @Override public int size() { return xs.count(); } @Override
public JmhMap put(JmhValue key, JmhValue value) {
msteindorfer/criterion
src/main/java/io/usethesource/criterion/generators/JmhHashedIntegerGenerator.java
// Path: src/main/java/io/usethesource/criterion/PureIntegerWithCustomHashCode.java // @CompilerControl(Mode.DONT_INLINE) // public class PureIntegerWithCustomHashCode implements JmhValue { // // private int value; // // PureIntegerWithCustomHashCode(int value) { // this.value = value; // } // // public static final PureIntegerWithCustomHashCode valueOf(int value) { // return new PureIntegerWithCustomHashCode(value); // } // // @Override // public int hashCode() { // int h = value ^ 0x85ebca6b; // // based on the final Avalanching phase of MurmurHash2 // // providing a nice mix of bits even for small numbers. // h ^= h >>> 13; // h *= 0x5bd1e995; // h ^= h >>> 15; // // return h; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof PureIntegerWithCustomHashCode) { // int otherValue = ((PureIntegerWithCustomHashCode) other).value; // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.criterion.PureIntegerWithCustomHashCode; import io.usethesource.criterion.api.JmhValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.generators; public class JmhHashedIntegerGenerator extends Generator<JmhValue> { public JmhHashedIntegerGenerator() { super(JmhValue.class); } @Override public JmhValue generate(SourceOfRandomness random, GenerationStatus status) {
// Path: src/main/java/io/usethesource/criterion/PureIntegerWithCustomHashCode.java // @CompilerControl(Mode.DONT_INLINE) // public class PureIntegerWithCustomHashCode implements JmhValue { // // private int value; // // PureIntegerWithCustomHashCode(int value) { // this.value = value; // } // // public static final PureIntegerWithCustomHashCode valueOf(int value) { // return new PureIntegerWithCustomHashCode(value); // } // // @Override // public int hashCode() { // int h = value ^ 0x85ebca6b; // // based on the final Avalanching phase of MurmurHash2 // // providing a nice mix of bits even for small numbers. // h ^= h >>> 13; // h *= 0x5bd1e995; // h ^= h >>> 15; // // return h; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof PureIntegerWithCustomHashCode) { // int otherValue = ((PureIntegerWithCustomHashCode) other).value; // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/generators/JmhHashedIntegerGenerator.java import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.criterion.PureIntegerWithCustomHashCode; import io.usethesource.criterion.api.JmhValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.generators; public class JmhHashedIntegerGenerator extends Generator<JmhValue> { public JmhHashedIntegerGenerator() { super(JmhValue.class); } @Override public JmhValue generate(SourceOfRandomness random, GenerationStatus status) {
return PureIntegerWithCustomHashCode.valueOf(random.nextInt());
msteindorfer/criterion
src/main/java/io/usethesource/criterion/generators/JmhSleepingIntegerGenerator.java
// Path: src/main/java/io/usethesource/criterion/SleepingInteger.java // @CompilerControl(Mode.DONT_INLINE) // public class SleepingInteger implements JmhValue { // // public static boolean IS_SLEEP_ENABLED_IN_HASHCODE = true; // public static boolean IS_SLEEP_ENABLED_IN_EQUALS = true; // // private static final int MAX_SLEEP_IN_MILLISECONDS = 0; // private static final int MAX_SLEEP_IN_NANOSECONDS = 10; // // private int value; // // public SleepingInteger(int value) { // this.value = value; // } // // protected void sleep(int base) { // try { // int timeMillis = // MAX_SLEEP_IN_MILLISECONDS == 0 ? 0 : Math.abs(base) % MAX_SLEEP_IN_MILLISECONDS; // // int timeNanos = MAX_SLEEP_IN_NANOSECONDS == 0 ? 0 : Math.abs(base) % MAX_SLEEP_IN_NANOSECONDS; // // // System.out.printf("Sleeping %dms\n", time); // // Thread.sleep(timeMillis, timeNanos); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // // TODO: have configurable WEIGHTS for hashCode() and equals() penalties. // // TODO: add caching to option to CHART (either keys, or keys + vals; in // // extra int[] array) // @Override // public int hashCode() { // if (IS_SLEEP_ENABLED_IN_HASHCODE) { // sleep(value); // } // return value; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof SleepingInteger) { // int otherValue = ((SleepingInteger) other).value; // // if (IS_SLEEP_ENABLED_IN_EQUALS) { // sleep(value + otherValue); // } // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // }
import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.criterion.SleepingInteger; import io.usethesource.criterion.api.JmhValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.generators; public class JmhSleepingIntegerGenerator extends Generator<JmhValue> { public JmhSleepingIntegerGenerator() { super(JmhValue.class); } @Override public JmhValue generate(SourceOfRandomness random, GenerationStatus status) {
// Path: src/main/java/io/usethesource/criterion/SleepingInteger.java // @CompilerControl(Mode.DONT_INLINE) // public class SleepingInteger implements JmhValue { // // public static boolean IS_SLEEP_ENABLED_IN_HASHCODE = true; // public static boolean IS_SLEEP_ENABLED_IN_EQUALS = true; // // private static final int MAX_SLEEP_IN_MILLISECONDS = 0; // private static final int MAX_SLEEP_IN_NANOSECONDS = 10; // // private int value; // // public SleepingInteger(int value) { // this.value = value; // } // // protected void sleep(int base) { // try { // int timeMillis = // MAX_SLEEP_IN_MILLISECONDS == 0 ? 0 : Math.abs(base) % MAX_SLEEP_IN_MILLISECONDS; // // int timeNanos = MAX_SLEEP_IN_NANOSECONDS == 0 ? 0 : Math.abs(base) % MAX_SLEEP_IN_NANOSECONDS; // // // System.out.printf("Sleeping %dms\n", time); // // Thread.sleep(timeMillis, timeNanos); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // // TODO: have configurable WEIGHTS for hashCode() and equals() penalties. // // TODO: add caching to option to CHART (either keys, or keys + vals; in // // extra int[] array) // @Override // public int hashCode() { // if (IS_SLEEP_ENABLED_IN_HASHCODE) { // sleep(value); // } // return value; // } // // @Override // public boolean equals(Object other) { // if (other == null) { // return false; // } // if (other == this) { // return true; // } // // if (other instanceof SleepingInteger) { // int otherValue = ((SleepingInteger) other).value; // // if (IS_SLEEP_ENABLED_IN_EQUALS) { // sleep(value + otherValue); // } // // return value == otherValue; // } // return false; // } // // @Override // public Object unwrap() { // return this; // cannot be unwrapped // } // // @Override // public String toString() { // return String.valueOf(value); // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // Path: src/main/java/io/usethesource/criterion/generators/JmhSleepingIntegerGenerator.java import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.criterion.SleepingInteger; import io.usethesource.criterion.api.JmhValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.generators; public class JmhSleepingIntegerGenerator extends Generator<JmhValue> { public JmhSleepingIntegerGenerator() { super(JmhValue.class); } @Override public JmhValue generate(SourceOfRandomness random, GenerationStatus status) {
return new SleepingInteger(random.nextInt());
msteindorfer/criterion
src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // }
import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class JmhTernaryRelationBenchmarks { public static final Class<? extends AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable>> generatorClass = TernaryTrieSetMultimapGenerator.class; /* * val l = (for (i <- 0 to 23) yield s"'${Math.pow(2, i).toInt}'") val r = (for (i <- 0 to 23) * yield s"'${Math.pow(2, i-1).toInt + Math.pow(2, i).toInt}'") val zipped = l zip r flatMap { * case (x,y) => List(x,y) } * * val all = zipped.drop(1).take(zipped.size - 2) all.mkString(", ").replace("'", "\"") */ @Param({"1", "2", "3", "4", "6", "8", "12", "16", "24", "32", "48", "64", "96", "128", "192", "256", "384", "512", "768", "1024", "1536", "2048", "3072", "4096", "6144", "8192", "12288", "16384", "24576", "32768", "49152", "65536", "98304", "131072", "196608", "262144", "393216", "524288", "786432", "1048576", "1572864", "2097152", "3145728", "4194304", "6291456", "8388608"}) protected int size; @Param({"0"}) // "1", "2", "3", "4", "5", "6", "7", "8", "9" protected int run;
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // } // Path: src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class JmhTernaryRelationBenchmarks { public static final Class<? extends AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable>> generatorClass = TernaryTrieSetMultimapGenerator.class; /* * val l = (for (i <- 0 to 23) yield s"'${Math.pow(2, i).toInt}'") val r = (for (i <- 0 to 23) * yield s"'${Math.pow(2, i-1).toInt + Math.pow(2, i).toInt}'") val zipped = l zip r flatMap { * case (x,y) => List(x,y) } * * val all = zipped.drop(1).take(zipped.size - 2) all.mkString(", ").replace("'", "\"") */ @Param({"1", "2", "3", "4", "6", "8", "12", "16", "24", "32", "48", "64", "96", "128", "192", "256", "384", "512", "768", "1024", "1536", "2048", "3072", "4096", "6144", "8192", "12288", "16384", "24576", "32768", "49152", "65536", "98304", "131072", "196608", "262144", "393216", "524288", "786432", "1048576", "1572864", "2097152", "3145728", "4194304", "6291456", "8388608"}) protected int size; @Param({"0"}) // "1", "2", "3", "4", "5", "6", "7", "8", "9" protected int run;
private TernaryRelation.Immutable<JmhValue, JmhValue, JmhValue, Triple<JmhValue, JmhValue, JmhValue>> testMap;
msteindorfer/criterion
src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // }
import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class JmhTernaryRelationBenchmarks { public static final Class<? extends AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable>> generatorClass = TernaryTrieSetMultimapGenerator.class; /* * val l = (for (i <- 0 to 23) yield s"'${Math.pow(2, i).toInt}'") val r = (for (i <- 0 to 23) * yield s"'${Math.pow(2, i-1).toInt + Math.pow(2, i).toInt}'") val zipped = l zip r flatMap { * case (x,y) => List(x,y) } * * val all = zipped.drop(1).take(zipped.size - 2) all.mkString(", ").replace("'", "\"") */ @Param({"1", "2", "3", "4", "6", "8", "12", "16", "24", "32", "48", "64", "96", "128", "192", "256", "384", "512", "768", "1024", "1536", "2048", "3072", "4096", "6144", "8192", "12288", "16384", "24576", "32768", "49152", "65536", "98304", "131072", "196608", "262144", "393216", "524288", "786432", "1048576", "1572864", "2097152", "3145728", "4194304", "6291456", "8388608"}) protected int size; @Param({"0"}) // "1", "2", "3", "4", "5", "6", "7", "8", "9" protected int run; private TernaryRelation.Immutable<JmhValue, JmhValue, JmhValue, Triple<JmhValue, JmhValue, JmhValue>> testMap; public JmhValue VALUE_EXISTING; public JmhValue VALUE_NOT_EXISTING; public static final int CACHED_NUMBERS_SIZE = 8; public JmhValue[] cachedNumbers = new JmhValue[CACHED_NUMBERS_SIZE]; public JmhValue[] cachedNumbersNotContained = new JmhValue[CACHED_NUMBERS_SIZE]; public static final Class<JmhValue> payloadToken = JmhValue.class; @Setup(Level.Trial) public void setUp() throws Exception { final Generator<JmhValue> itemGenerator; final Generator<Triple> tripleGenerator; final AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable> collectionGenerator; final SourceOfRandomness random = freshRandom.get(); final GenerationStatus status = freshGenerationStatus.apply(random); try {
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // } // Path: src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class JmhTernaryRelationBenchmarks { public static final Class<? extends AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable>> generatorClass = TernaryTrieSetMultimapGenerator.class; /* * val l = (for (i <- 0 to 23) yield s"'${Math.pow(2, i).toInt}'") val r = (for (i <- 0 to 23) * yield s"'${Math.pow(2, i-1).toInt + Math.pow(2, i).toInt}'") val zipped = l zip r flatMap { * case (x,y) => List(x,y) } * * val all = zipped.drop(1).take(zipped.size - 2) all.mkString(", ").replace("'", "\"") */ @Param({"1", "2", "3", "4", "6", "8", "12", "16", "24", "32", "48", "64", "96", "128", "192", "256", "384", "512", "768", "1024", "1536", "2048", "3072", "4096", "6144", "8192", "12288", "16384", "24576", "32768", "49152", "65536", "98304", "131072", "196608", "262144", "393216", "524288", "786432", "1048576", "1572864", "2097152", "3145728", "4194304", "6291456", "8388608"}) protected int size; @Param({"0"}) // "1", "2", "3", "4", "5", "6", "7", "8", "9" protected int run; private TernaryRelation.Immutable<JmhValue, JmhValue, JmhValue, Triple<JmhValue, JmhValue, JmhValue>> testMap; public JmhValue VALUE_EXISTING; public JmhValue VALUE_NOT_EXISTING; public static final int CACHED_NUMBERS_SIZE = 8; public JmhValue[] cachedNumbers = new JmhValue[CACHED_NUMBERS_SIZE]; public JmhValue[] cachedNumbersNotContained = new JmhValue[CACHED_NUMBERS_SIZE]; public static final Class<JmhValue> payloadToken = JmhValue.class; @Setup(Level.Trial) public void setUp() throws Exception { final Generator<JmhValue> itemGenerator; final Generator<Triple> tripleGenerator; final AbstractTernaryRelationGenerator<? extends TernaryRelation.Immutable> collectionGenerator; final SourceOfRandomness random = freshRandom.get(); final GenerationStatus status = freshGenerationStatus.apply(random); try {
itemGenerator = new JmhIntegerGenerator();
msteindorfer/criterion
src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // }
import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue;
} // assert (contained) assert Stream.of(cachedNumbers) .allMatch(sample -> testMap.contains(Triple.of(sample, sample, sample))); /* * generate random integers that are not yet contained in the data set */ for (int i = 0; i < CACHED_NUMBERS_SIZE; i++) { boolean found = false; while (!found) { final JmhValue candidate = itemGenerator.generate(random, status); if (!elements.contains(candidate)) { cachedNumbersNotContained[i] = candidate; found = true; } } } // assert (contained) assert Stream.of(cachedNumbersNotContained) .noneMatch(sample -> testMap.contains(Triple.of(sample, sample, sample))); VALUE_EXISTING = cachedNumbers[0]; VALUE_NOT_EXISTING = cachedNumbersNotContained[0]; } private final Supplier<SourceOfRandomness> freshRandom = () -> new SourceOfRandomness(
// Path: src/main/java/io/usethesource/criterion/BenchmarkUtils.java // public static int seedFromSizeAndRun(int size, int run) { // return mix(size) ^ mix(run); // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValue.java // @CompilerControl(Mode.DONT_INLINE) // public interface JmhValue { // // /** // * Removes the JmhValue delegation object to reveal its internal representation. // * // * @return internal representation // */ // Object unwrap(); // // } // // Path: src/main/java/io/usethesource/criterion/generators/JmhIntegerGenerator.java // public class JmhIntegerGenerator extends Generator<JmhValue> { // // public JmhIntegerGenerator() { // super(JmhValue.class); // } // // @Override // public JmhValue generate(SourceOfRandomness random, GenerationStatus status) { // return new PureInteger(random.nextInt()); // } // // } // Path: src/main/java/io/usethesource/criterion/JmhTernaryRelationBenchmarks.java import static io.usethesource.criterion.BenchmarkUtils.seedFromSizeAndRun; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.internal.GeometricDistribution; import com.pholser.junit.quickcheck.internal.generator.SimpleGenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import io.usethesource.capsule.Set; import io.usethesource.capsule.api.TernaryRelation; import io.usethesource.capsule.api.Triple; import io.usethesource.capsule.generators.SingletonToTripleGenerator; import io.usethesource.capsule.generators.relation.AbstractTernaryRelationGenerator; import io.usethesource.capsule.generators.relation.TernaryTrieSetMultimapGenerator; import io.usethesource.capsule.util.stream.CapsuleCollectors; import io.usethesource.criterion.api.JmhValue; import io.usethesource.criterion.generators.JmhIntegerGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; } // assert (contained) assert Stream.of(cachedNumbers) .allMatch(sample -> testMap.contains(Triple.of(sample, sample, sample))); /* * generate random integers that are not yet contained in the data set */ for (int i = 0; i < CACHED_NUMBERS_SIZE; i++) { boolean found = false; while (!found) { final JmhValue candidate = itemGenerator.generate(random, status); if (!elements.contains(candidate)) { cachedNumbersNotContained[i] = candidate; found = true; } } } // assert (contained) assert Stream.of(cachedNumbersNotContained) .noneMatch(sample -> testMap.contains(Triple.of(sample, sample, sample))); VALUE_EXISTING = cachedNumbers[0]; VALUE_NOT_EXISTING = cachedNumbersNotContained[0]; } private final Supplier<SourceOfRandomness> freshRandom = () -> new SourceOfRandomness(
new Random(seedFromSizeAndRun(size, run)));
msteindorfer/criterion
src/main/java/io/usethesource/criterion/impl/persistent/pcollections/PcollectionsValueFactory.java
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // }
import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory;
/** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.pcollections; public class PcollectionsValueFactory implements JmhValueFactory { @Override
// Path: src/main/java/io/usethesource/criterion/api/JmhMap.java // public interface JmhMap extends Iterable<JmhValue>, JmhValue { // // public boolean isEmpty(); // // public int size(); // // public JmhMap put(JmhValue key, JmhValue value); // // public JmhMap removeKey(JmhValue key); // // /** // * @return the value that is mapped to this key, or null if no such value exists // */ // public JmhValue get(JmhValue key); // // public boolean containsKey(JmhValue key); // // public boolean containsValue(JmhValue value); // // /** // * @return an iterator over the keys of the map // */ // @Override // public Iterator<JmhValue> iterator(); // // /** // * @return an iterator over the values of the map // */ // public Iterator<JmhValue> valueIterator(); // // /** // * @return an iterator over the keys-value pairs of the map // */ // public Iterator<Entry<JmhValue, JmhValue>> entryIterator(); // // public static interface Builder extends JmhBuilder { // // void put(JmhValue key, JmhValue value); // // void putAll(JmhMap map); // // void putAll(Map<JmhValue, JmhValue> map); // // @Override // JmhMap done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhSet.java // public interface JmhSet extends JmhValue, Iterable<JmhValue> { // // boolean isEmpty(); // // int size(); // // boolean contains(JmhValue element); // // JmhSet insert(JmhValue element); // // JmhSet delete(JmhValue elem); // // default boolean subsetOf(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet union(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet subtract(JmhSet other) { // throw new UnsupportedOperationException(); // } // // default JmhSet intersect(JmhSet other) { // throw new UnsupportedOperationException(); // } // // @Override // Iterator<JmhValue> iterator(); // // @Deprecated // java.util.Set<JmhValue> asJavaSet(); // // interface Builder extends JmhBuilder { // // @Deprecated // default void insert(JmhValue value) { // insert(new JmhValue[]{value}); // } // // void insert(JmhValue... v); // // void insertAll(Iterable<? extends JmhValue> collection); // // @Override // JmhSet done(); // // } // // } // // Path: src/main/java/io/usethesource/criterion/api/JmhValueFactory.java // public interface JmhValueFactory { // // static RuntimeException FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION = // new UnsupportedOperationException("Not yet implemented."); // // // default JmhSet set() { // // return setBuilder().done(); // // } // // default JmhSet.Builder setBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhMap map() { // // return mapBuilder().done(); // // } // // default JmhMap.Builder mapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // // default JmhSetMultimap setMulimap() { // // return setMultimapBuilder().done(); // // } // // default JmhSetMultimap.Builder setMultimapBuilder() { // throw FACTORY_NOT_YET_IMPLEMENTED_EXCEPTION; // } // // } // Path: src/main/java/io/usethesource/criterion/impl/persistent/pcollections/PcollectionsValueFactory.java import io.usethesource.criterion.api.JmhMap; import io.usethesource.criterion.api.JmhSet; import io.usethesource.criterion.api.JmhValueFactory; /** * Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors. * All rights reserved. * * This file is licensed under the BSD 2-Clause License, which accompanies this project * and is available under https://opensource.org/licenses/BSD-2-Clause. */ package io.usethesource.criterion.impl.persistent.pcollections; public class PcollectionsValueFactory implements JmhValueFactory { @Override
public JmhSet.Builder setBuilder() {