text
stringlengths
7
1.01M
package model; import java.sql.Date; public class Withdrawl { private int withdrawl_ID; private int amount; private Date dateOfWithdrawl; public Withdrawl() { } public Withdrawl(int withdrawl_ID, int amount, Date dateOfWithdrawl) { super(); this.withdrawl_ID = withdrawl_ID; this.amount = amount; this.dateOfWithdrawl = dateOfWithdrawl; } public int getWithdrawl_ID() { return this.withdrawl_ID; } public void setWithdrawl_ID(int withdrawl_ID) { this.withdrawl_ID = withdrawl_ID; } public int getAmount() { return this.amount; } public void setAmount(int amount) { this.amount = amount; } public Date getDateOfWithdrawl() { return this.dateOfWithdrawl; } public void setDateOfWithdrawl(Date dateOfWithdrawl) { this.dateOfWithdrawl = dateOfWithdrawl; } }
package com.agenda; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class AddEvent extends AppCompatActivity { InternalStorageManagement taskDB; Button button; EditText _title, _due, _priority; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_event_activity); taskDB = new InternalStorageManagement(this); button = (Button) findViewById(R.id.button_save); _title = (EditText) findViewById(R.id.Title); _due = (EditText) findViewById(R.id.Due); _priority = (EditText) findViewById(R.id.Priority); save(); } public void save() { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddEvent.this, ListViewContents.class); String title = _title.getText().toString(); String due = _due.getText().toString(); String priority = _priority.getText().toString(); boolean insertData = taskDB.addData(title, due, priority); if(insertData) { Toast.makeText(AddEvent.this, "Data was succesfully saved", Toast.LENGTH_LONG).show(); startActivity(intent); } } }); } }
package com.jzy.manager.exception; import lombok.Getter; /** * @ClassName ExcelTooManyRowsException * @Author JinZhiyun * @Description 表格行数过多异常 * @Date 2020/1/12 13:08 * @Version 1.0 **/ public class ExcelTooManyRowsException extends Exception { private static final long serialVersionUID = 7254716126055023396L; /** * 实际的行数 */ @Getter private int actualRowCount; /** * 行数最大限制 */ @Getter private int rowCountThreshold; public ExcelTooManyRowsException() { } public ExcelTooManyRowsException(String message) { super(message); } /** * 构造表格行数过多异常,入参具体的行数上限maxRowCount和实际行数 * * @param message 异常描述 * @param maxRowCount 最大行数限制 * @param actualRowCount 最大行数限制 */ public ExcelTooManyRowsException(String message, int maxRowCount, int actualRowCount) { super(message); this.rowCountThreshold = maxRowCount; this.actualRowCount=actualRowCount; } /** * 构造表格行数过多异常,入参具体的行数上限maxRowCount和实际行数 * * @param maxRowCount 最大行数限制 */ public ExcelTooManyRowsException(int maxRowCount, int actualRowCount) { super("输入表格的行数过多。最大行数限制:" + maxRowCount+ ",实际行数:"+actualRowCount); this.rowCountThreshold = maxRowCount; this.actualRowCount=actualRowCount; } }
/* * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.net.URI; import java.net.URL; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.List; import java.util.ArrayList; import java.security.SecureRandom; import java.nio.file.Path; import java.nio.file.FileSystems; import sun.security.action.GetPropertyAction; /** * An abstract representation of file and directory pathnames. * * <p> User interfaces and operating systems use system-dependent <em>pathname * strings</em> to name files and directories. This class presents an * abstract, system-independent view of hierarchical pathnames. An * <em>abstract pathname</em> has two components: * * <ol> * <li> An optional system-dependent <em>prefix</em> string, * such as a disk-drive specifier, <code>"/"</code>&nbsp;for the UNIX root * directory, or <code>"\\\\"</code>&nbsp;for a Microsoft Windows UNC pathname, and * <li> A sequence of zero or more string <em>names</em>. * </ol> * * The first name in an abstract pathname may be a directory name or, in the * case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name * in an abstract pathname denotes a directory; the last name may denote * either a directory or a file. The <em>empty</em> abstract pathname has no * prefix and an empty name sequence. * * <p> The conversion of a pathname string to or from an abstract pathname is * inherently system-dependent. When an abstract pathname is converted into a * pathname string, each name is separated from the next by a single copy of * the default <em>separator character</em>. The default name-separator * character is defined by the system property <code>file.separator</code>, and * is made available in the public static fields {@link * #separator} and {@link #separatorChar} of this class. * When a pathname string is converted into an abstract pathname, the names * within it may be separated by the default name-separator character or by any * other name-separator character that is supported by the underlying system. * * <p> A pathname, whether abstract or in string form, may be either * <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in * that no other information is required in order to locate the file that it * denotes. A relative pathname, in contrast, must be interpreted in terms of * information taken from some other pathname. By default the classes in the * <code>java.io</code> package always resolve relative pathnames against the * current user directory. This directory is named by the system property * <code>user.dir</code>, and is typically the directory in which the Java * virtual machine was invoked. * * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking * the {@link #getParent} method of this class and consists of the pathname's * prefix and each name in the pathname's name sequence except for the last. * Each directory's absolute pathname is an ancestor of any {@code File} * object with an absolute abstract pathname which begins with the directory's * absolute pathname. For example, the directory denoted by the abstract * pathname {@code "/usr"} is an ancestor of the directory denoted by the * pathname {@code "/usr/local/bin"}. * * <p> The prefix concept is used to handle root directories on UNIX platforms, * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, * as follows: * * <ul> * * <li> For UNIX platforms, the prefix of an absolute pathname is always * <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname * denoting the root directory has the prefix <code>"/"</code> and an empty * name sequence. * * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive * specifier consists of the drive letter followed by <code>":"</code> and * possibly followed by <code>"\\"</code> if the pathname is absolute. The * prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share * name are the first two names in the name sequence. A relative pathname that * does not specify a drive has no prefix. * * </ul> * * <p> Instances of this class may or may not denote an actual file-system * object such as a file or a directory. If it does denote such an object * then that object resides in a <i>partition</i>. A partition is an * operating system-specific portion of storage for a file system. A single * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may * contain multiple partitions. The object, if any, will reside on the * partition <a id="partName">named</a> by some ancestor of the absolute * form of this pathname. * * <p> A file system may implement restrictions to certain operations on the * actual file-system object, such as reading, writing, and executing. These * restrictions are collectively known as <i>access permissions</i>. The file * system may have multiple sets of access permissions on a single object. * For example, one set may apply to the object's <i>owner</i>, and another * may apply to all other users. The access permissions on an object may * cause some methods in this class to fail. * * <p> Instances of the <code>File</code> class are immutable; that is, once * created, the abstract pathname represented by a <code>File</code> object * will never change. * * <h3>Interoperability with {@code java.nio.file} package</h3> * * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a> * package defines interfaces and classes for the Java virtual machine to access * files, file attributes, and file systems. This API may be used to overcome * many of the limitations of the {@code java.io.File} class. * The {@link #toPath toPath} method may be used to obtain a {@link * Path} that uses the abstract path represented by a {@code File} object to * locate a file. The resulting {@code Path} may be used with the {@link * java.nio.file.Files} class to provide more efficient and extensive access to * additional file operations, file attributes, and I/O exceptions to help * diagnose errors when an operation on a file fails. * * @author unascribed * @since 1.0 */ public class File implements Serializable, Comparable<File> { /** * The FileSystem object representing the platform's local file system. */ private static final FileSystem fs = DefaultFileSystem.getFileSystem(); /** * This abstract pathname's normalized pathname string. A normalized * pathname string uses the default name-separator character and does not * contain any duplicate or redundant separators. * * @serial */ private final String path; /** * Enum type that indicates the status of a file path. */ private static enum PathStatus { INVALID, CHECKED }; /** * The flag indicating whether the file path is invalid. */ private transient PathStatus status = null; /** * Check if the file has an invalid path. Currently, the inspection of * a file path is very limited, and it only covers Nul character check. * Returning true means the path is definitely invalid/garbage. But * returning false does not guarantee that the path is valid. * * @return true if the file path is invalid. */ final boolean isInvalid() { PathStatus s = status; if (s == null) { s = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED : PathStatus.INVALID; status = s; } return s == PathStatus.INVALID; } /** * The length of this abstract pathname's prefix, or zero if it has no * prefix. */ private final transient int prefixLength; /** * Returns the length of this abstract pathname's prefix. * For use by FileSystem classes. */ int getPrefixLength() { return prefixLength; } /** * The system-dependent default name-separator character. This field is * initialized to contain the first character of the value of the system * property <code>file.separator</code>. On UNIX systems the value of this * field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>. * * @see java.lang.System#getProperty(java.lang.String) */ public static final char separatorChar = fs.getSeparator(); /** * The system-dependent default name-separator character, represented as a * string for convenience. This string contains a single character, namely * {@link #separatorChar}. */ public static final String separator = "" + separatorChar; /** * The system-dependent path-separator character. This field is * initialized to contain the first character of the value of the system * property <code>path.separator</code>. This character is used to * separate filenames in a sequence of files given as a <em>path list</em>. * On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it * is <code>';'</code>. * * @see java.lang.System#getProperty(java.lang.String) */ public static final char pathSeparatorChar = fs.getPathSeparator(); /** * The system-dependent path-separator character, represented as a string * for convenience. This string contains a single character, namely * {@link #pathSeparatorChar}. */ public static final String pathSeparator = "" + pathSeparatorChar; /* -- Constructors -- */ /** * Internal constructor for already-normalized pathname strings. */ private File(String pathname, int prefixLength) { this.path = pathname; this.prefixLength = prefixLength; } /** * Internal constructor for already-normalized pathname strings. * The parameter order is used to disambiguate this method from the * public(File, String) constructor. */ private File(String child, File parent) { assert parent.path != null; assert (!parent.path.equals("")); this.path = fs.resolve(parent.path, child); this.prefixLength = parent.prefixLength; } /** * Creates a new <code>File</code> instance by converting the given * pathname string into an abstract pathname. If the given string is * the empty string, then the result is the empty abstract pathname. * * @param pathname A pathname string * @throws NullPointerException * If the <code>pathname</code> argument is <code>null</code> */ public File(String pathname) { if (pathname == null) { throw new NullPointerException(); } this.path = fs.normalize(pathname); this.prefixLength = fs.prefixLength(this.path); } /* Note: The two-argument File constructors do not interpret an empty parent abstract pathname as the current user directory. An empty parent instead causes the child to be resolved against the system-dependent directory defined by the FileSystem.getDefaultParent method. On Unix this default is "/", while on Microsoft Windows it is "\\". This is required for compatibility with the original behavior of this class. */ /** * Creates a new <code>File</code> instance from a parent pathname string * and a child pathname string. * * <p> If <code>parent</code> is <code>null</code> then the new * <code>File</code> instance is created as if by invoking the * single-argument <code>File</code> constructor on the given * <code>child</code> pathname string. * * <p> Otherwise the <code>parent</code> pathname string is taken to denote * a directory, and the <code>child</code> pathname string is taken to * denote either a directory or a file. If the <code>child</code> pathname * string is absolute then it is converted into a relative pathname in a * system-dependent way. If <code>parent</code> is the empty string then * the new <code>File</code> instance is created by converting * <code>child</code> into an abstract pathname and resolving the result * against a system-dependent default directory. Otherwise each pathname * string is converted into an abstract pathname and the child abstract * pathname is resolved against the parent. * * @param parent The parent pathname string * @param child The child pathname string * @throws NullPointerException * If <code>child</code> is <code>null</code> */ public File(String parent, String child) { if (child == null) { throw new NullPointerException(); } if (parent != null) { if (parent.equals("")) { this.path = fs.resolve(fs.getDefaultParent(), fs.normalize(child)); } else { this.path = fs.resolve(fs.normalize(parent), fs.normalize(child)); } } else { this.path = fs.normalize(child); } this.prefixLength = fs.prefixLength(this.path); } /** * Creates a new <code>File</code> instance from a parent abstract * pathname and a child pathname string. * * <p> If <code>parent</code> is <code>null</code> then the new * <code>File</code> instance is created as if by invoking the * single-argument <code>File</code> constructor on the given * <code>child</code> pathname string. * * <p> Otherwise the <code>parent</code> abstract pathname is taken to * denote a directory, and the <code>child</code> pathname string is taken * to denote either a directory or a file. If the <code>child</code> * pathname string is absolute then it is converted into a relative * pathname in a system-dependent way. If <code>parent</code> is the empty * abstract pathname then the new <code>File</code> instance is created by * converting <code>child</code> into an abstract pathname and resolving * the result against a system-dependent default directory. Otherwise each * pathname string is converted into an abstract pathname and the child * abstract pathname is resolved against the parent. * * @param parent The parent abstract pathname * @param child The child pathname string * @throws NullPointerException * If <code>child</code> is <code>null</code> */ public File(File parent, String child) { if (child == null) { throw new NullPointerException(); } if (parent != null) { if (parent.path.equals("")) { this.path = fs.resolve(fs.getDefaultParent(), fs.normalize(child)); } else { this.path = fs.resolve(parent.path, fs.normalize(child)); } } else { this.path = fs.normalize(child); } this.prefixLength = fs.prefixLength(this.path); } /** * Creates a new {@code File} instance by converting the given * {@code file:} URI into an abstract pathname. * * <p> The exact form of a {@code file:} URI is system-dependent, hence * the transformation performed by this constructor is also * system-dependent. * * <p> For a given abstract pathname <i>f</i> it is guaranteed that * * <blockquote><code> * new File(</code><i>&nbsp;f</i><code>.{@link #toURI() * toURI}()).equals(</code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}()) * </code></blockquote> * * so long as the original abstract pathname, the URI, and the new abstract * pathname are all created in (possibly different invocations of) the same * Java virtual machine. This relationship typically does not hold, * however, when a {@code file:} URI that is created in a virtual machine * on one operating system is converted into an abstract pathname in a * virtual machine on a different operating system. * * @param uri * An absolute, hierarchical URI with a scheme equal to * {@code "file"}, a non-empty path component, and undefined * authority, query, and fragment components * * @throws NullPointerException * If {@code uri} is {@code null} * * @throws IllegalArgumentException * If the preconditions on the parameter do not hold * * @see #toURI() * @see java.net.URI * @since 1.4 */ public File(URI uri) { // Check our many preconditions if (!uri.isAbsolute()) throw new IllegalArgumentException("URI is not absolute"); if (uri.isOpaque()) throw new IllegalArgumentException("URI is not hierarchical"); String scheme = uri.getScheme(); if ((scheme == null) || !scheme.equalsIgnoreCase("file")) throw new IllegalArgumentException("URI scheme is not \"file\""); if (uri.getRawAuthority() != null) throw new IllegalArgumentException("URI has an authority component"); if (uri.getRawFragment() != null) throw new IllegalArgumentException("URI has a fragment component"); if (uri.getRawQuery() != null) throw new IllegalArgumentException("URI has a query component"); String p = uri.getPath(); if (p.equals("")) throw new IllegalArgumentException("URI path component is empty"); // Okay, now initialize p = fs.fromURIPath(p); if (File.separatorChar != '/') p = p.replace('/', File.separatorChar); this.path = fs.normalize(p); this.prefixLength = fs.prefixLength(this.path); } /* -- Path-component accessors -- */ /** * Returns the name of the file or directory denoted by this abstract * pathname. This is just the last name in the pathname's name * sequence. If the pathname's name sequence is empty, then the empty * string is returned. * * @return The name of the file or directory denoted by this abstract * pathname, or the empty string if this pathname's name sequence * is empty */ public String getName() { int index = path.lastIndexOf(separatorChar); if (index < prefixLength) return path.substring(prefixLength); return path.substring(index + 1); } /** * Returns the pathname string of this abstract pathname's parent, or * <code>null</code> if this pathname does not name a parent directory. * * <p> The <em>parent</em> of an abstract pathname consists of the * pathname's prefix, if any, and each name in the pathname's name * sequence except for the last. If the name sequence is empty then * the pathname does not name a parent directory. * * @return The pathname string of the parent directory named by this * abstract pathname, or <code>null</code> if this pathname * does not name a parent */ public String getParent() { int index = path.lastIndexOf(separatorChar); if (index < prefixLength) { if ((prefixLength > 0) && (path.length() > prefixLength)) return path.substring(0, prefixLength); return null; } return path.substring(0, index); } /** * Returns the abstract pathname of this abstract pathname's parent, * or <code>null</code> if this pathname does not name a parent * directory. * * <p> The <em>parent</em> of an abstract pathname consists of the * pathname's prefix, if any, and each name in the pathname's name * sequence except for the last. If the name sequence is empty then * the pathname does not name a parent directory. * * @return The abstract pathname of the parent directory named by this * abstract pathname, or <code>null</code> if this pathname * does not name a parent * * @since 1.2 */ public File getParentFile() { String p = this.getParent(); if (p == null) return null; if (getClass() != File.class) { p = fs.normalize(p); } return new File(p, this.prefixLength); } /** * Converts this abstract pathname into a pathname string. The resulting * string uses the {@link #separator default name-separator character} to * separate the names in the name sequence. * * @return The string form of this abstract pathname */ public String getPath() { return path; } /* -- Path operations -- */ /** * Tests whether this abstract pathname is absolute. The definition of * absolute pathname is system dependent. On UNIX systems, a pathname is * absolute if its prefix is <code>"/"</code>. On Microsoft Windows systems, a * pathname is absolute if its prefix is a drive specifier followed by * <code>"\\"</code>, or if its prefix is <code>"\\\\"</code>. * * @return <code>true</code> if this abstract pathname is absolute, * <code>false</code> otherwise */ public boolean isAbsolute() { return fs.isAbsolute(this); } /** * Returns the absolute pathname string of this abstract pathname. * * <p> If this abstract pathname is already absolute, then the pathname * string is simply returned as if by the {@link #getPath} * method. If this abstract pathname is the empty abstract pathname then * the pathname string of the current user directory, which is named by the * system property <code>user.dir</code>, is returned. Otherwise this * pathname is resolved in a system-dependent way. On UNIX systems, a * relative pathname is made absolute by resolving it against the current * user directory. On Microsoft Windows systems, a relative pathname is made absolute * by resolving it against the current directory of the drive named by the * pathname, if any; if not, it is resolved against the current user * directory. * * @return The absolute pathname string denoting the same file or * directory as this abstract pathname * * @throws SecurityException * If a required system property value cannot be accessed. * * @see java.io.File#isAbsolute() */ public String getAbsolutePath() { return fs.resolve(this); } /** * Returns the absolute form of this abstract pathname. Equivalent to * <code>new&nbsp;File(this.{@link #getAbsolutePath})</code>. * * @return The absolute abstract pathname denoting the same file or * directory as this abstract pathname * * @throws SecurityException * If a required system property value cannot be accessed. * * @since 1.2 */ public File getAbsoluteFile() { String absPath = getAbsolutePath(); if (getClass() != File.class) { absPath = fs.normalize(absPath); } return new File(absPath, fs.prefixLength(absPath)); } /** * Returns the canonical pathname string of this abstract pathname. * * <p> A canonical pathname is both absolute and unique. The precise * definition of canonical form is system-dependent. This method first * converts this pathname to absolute form if necessary, as if by invoking the * {@link #getAbsolutePath} method, and then maps it to its unique form in a * system-dependent way. This typically involves removing redundant names * such as {@code "."} and {@code ".."} from the pathname, resolving * symbolic links (on UNIX platforms), and converting drive letters to a * standard case (on Microsoft Windows platforms). * * <p> Every pathname that denotes an existing file or directory has a * unique canonical form. Every pathname that denotes a nonexistent file * or directory also has a unique canonical form. The canonical form of * the pathname of a nonexistent file or directory may be different from * the canonical form of the same pathname after the file or directory is * created. Similarly, the canonical form of the pathname of an existing * file or directory may be different from the canonical form of the same * pathname after the file or directory is deleted. * * @return The canonical pathname string denoting the same file or * directory as this abstract pathname * * @throws IOException * If an I/O error occurs, which is possible because the * construction of the canonical pathname may require * filesystem queries * * @throws SecurityException * If a required system property value cannot be accessed, or * if a security manager exists and its {@link * java.lang.SecurityManager#checkRead} method denies * read access to the file * * @since 1.1 * @see Path#toRealPath */ public String getCanonicalPath() throws IOException { if (isInvalid()) { throw new IOException("Invalid file path"); } return fs.canonicalize(fs.resolve(this)); } /** * Returns the canonical form of this abstract pathname. Equivalent to * <code>new&nbsp;File(this.{@link #getCanonicalPath})</code>. * * @return The canonical pathname string denoting the same file or * directory as this abstract pathname * * @throws IOException * If an I/O error occurs, which is possible because the * construction of the canonical pathname may require * filesystem queries * * @throws SecurityException * If a required system property value cannot be accessed, or * if a security manager exists and its {@link * java.lang.SecurityManager#checkRead} method denies * read access to the file * * @since 1.2 * @see Path#toRealPath */ public File getCanonicalFile() throws IOException { String canonPath = getCanonicalPath(); if (getClass() != File.class) { canonPath = fs.normalize(canonPath); } return new File(canonPath, fs.prefixLength(canonPath)); } private static String slashify(String path, boolean isDirectory) { String p = path; if (File.separatorChar != '/') p = p.replace(File.separatorChar, '/'); if (!p.startsWith("/")) p = "/" + p; if (!p.endsWith("/") && isDirectory) p = p + "/"; return p; } /** * Converts this abstract pathname into a <code>file:</code> URL. The * exact form of the URL is system-dependent. If it can be determined that * the file denoted by this abstract pathname is a directory, then the * resulting URL will end with a slash. * * @return A URL object representing the equivalent file URL * * @throws MalformedURLException * If the path cannot be parsed as a URL * * @see #toURI() * @see java.net.URI * @see java.net.URI#toURL() * @see java.net.URL * @since 1.2 * * @deprecated This method does not automatically escape characters that * are illegal in URLs. It is recommended that new code convert an * abstract pathname into a URL by first converting it into a URI, via the * {@link #toURI() toURI} method, and then converting the URI into a URL * via the {@link java.net.URI#toURL() URI.toURL} method. */ @Deprecated public URL toURL() throws MalformedURLException { if (isInvalid()) { throw new MalformedURLException("Invalid file path"); } return new URL("file", "", slashify(getAbsolutePath(), isDirectory())); } /** * Constructs a {@code file:} URI that represents this abstract pathname. * * <p> The exact form of the URI is system-dependent. If it can be * determined that the file denoted by this abstract pathname is a * directory, then the resulting URI will end with a slash. * * <p> For a given abstract pathname <i>f</i>, it is guaranteed that * * <blockquote><code> * new {@link #File(java.net.URI) File}(</code><i>&nbsp;f</i><code>.toURI()).equals( * </code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}()) * </code></blockquote> * * so long as the original abstract pathname, the URI, and the new abstract * pathname are all created in (possibly different invocations of) the same * Java virtual machine. Due to the system-dependent nature of abstract * pathnames, however, this relationship typically does not hold when a * {@code file:} URI that is created in a virtual machine on one operating * system is converted into an abstract pathname in a virtual machine on a * different operating system. * * <p> Note that when this abstract pathname represents a UNC pathname then * all components of the UNC (including the server name component) are encoded * in the {@code URI} path. The authority component is undefined, meaning * that it is represented as {@code null}. The {@link Path} class defines the * {@link Path#toUri toUri} method to encode the server name in the authority * component of the resulting {@code URI}. The {@link #toPath toPath} method * may be used to obtain a {@code Path} representing this abstract pathname. * * @return An absolute, hierarchical URI with a scheme equal to * {@code "file"}, a path representing this abstract pathname, * and undefined authority, query, and fragment components * @throws SecurityException If a required system property value cannot * be accessed. * * @see #File(java.net.URI) * @see java.net.URI * @see java.net.URI#toURL() * @since 1.4 */ public URI toURI() { try { File f = getAbsoluteFile(); String sp = slashify(f.getPath(), f.isDirectory()); if (sp.startsWith("//")) sp = "//" + sp; return new URI("file", null, sp, null); } catch (URISyntaxException x) { throw new Error(x); // Can't happen } } /* -- Attribute accessors -- */ /** * Tests whether the application can read the file denoted by this * abstract pathname. On some platforms it may be possible to start the * Java virtual machine with special privileges that allow it to read * files that are marked as unreadable. Consequently this method may return * {@code true} even though the file does not have read permissions. * * @return <code>true</code> if and only if the file specified by this * abstract pathname exists <em>and</em> can be read by the * application; <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file */ public boolean canRead() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_READ); } /** * Tests whether the application can modify the file denoted by this * abstract pathname. On some platforms it may be possible to start the * Java virtual machine with special privileges that allow it to modify * files that are marked read-only. Consequently this method may return * {@code true} even though the file is marked read-only. * * @return <code>true</code> if and only if the file system actually * contains a file denoted by this abstract pathname <em>and</em> * the application is allowed to write to the file; * <code>false</code> otherwise. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file */ public boolean canWrite() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_WRITE); } /** * Tests whether the file or directory denoted by this abstract pathname * exists. * * @return <code>true</code> if and only if the file or directory denoted * by this abstract pathname exists; <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file or directory */ public boolean exists() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0); } /** * Tests whether the file denoted by this abstract pathname is a * directory. * * <p> Where it is required to distinguish an I/O exception from the case * that the file is not a directory, or where several attributes of the * same file are required at the same time, then the {@link * java.nio.file.Files#readAttributes(Path,Class,LinkOption[]) * Files.readAttributes} method may be used. * * @return <code>true</code> if and only if the file denoted by this * abstract pathname exists <em>and</em> is a directory; * <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file */ public boolean isDirectory() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY) != 0); } /** * Tests whether the file denoted by this abstract pathname is a normal * file. A file is <em>normal</em> if it is not a directory and, in * addition, satisfies other system-dependent criteria. Any non-directory * file created by a Java application is guaranteed to be a normal file. * * <p> Where it is required to distinguish an I/O exception from the case * that the file is not a normal file, or where several attributes of the * same file are required at the same time, then the {@link * java.nio.file.Files#readAttributes(Path,Class,LinkOption[]) * Files.readAttributes} method may be used. * * @return <code>true</code> if and only if the file denoted by this * abstract pathname exists <em>and</em> is a normal file; * <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file */ public boolean isFile() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0); } /** * Tests whether the file named by this abstract pathname is a hidden * file. The exact definition of <em>hidden</em> is system-dependent. On * UNIX systems, a file is considered to be hidden if its name begins with * a period character (<code>'.'</code>). On Microsoft Windows systems, a file is * considered to be hidden if it has been marked as such in the filesystem. * * @return <code>true</code> if and only if the file denoted by this * abstract pathname is hidden according to the conventions of the * underlying platform * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file * * @since 1.2 */ public boolean isHidden() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0); } /** * Returns the time that the file denoted by this abstract pathname was * last modified. * * @apiNote * While the unit of time of the return value is milliseconds, the * granularity of the value depends on the underlying file system and may * be larger. For example, some file systems use time stamps in units of * seconds. * * <p> Where it is required to distinguish an I/O exception from the case * where {@code 0L} is returned, or where several attributes of the * same file are required at the same time, or where the time of last * access or the creation time are required, then the {@link * java.nio.file.Files#readAttributes(Path,Class,LinkOption[]) * Files.readAttributes} method may be used. If however only the * time of last modification is required, then the * {@link java.nio.file.Files#getLastModifiedTime(Path,LinkOption[]) * Files.getLastModifiedTime} method may be used instead. * * @return A <code>long</code> value representing the time the file was * last modified, measured in milliseconds since the epoch * (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the * file does not exist or if an I/O error occurs. The value may * be negative indicating the number of milliseconds before the * epoch * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file */ public long lastModified() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getLastModifiedTime(this); } /** * Returns the length of the file denoted by this abstract pathname. * The return value is unspecified if this pathname denotes a directory. * * <p> Where it is required to distinguish an I/O exception from the case * that {@code 0L} is returned, or where several attributes of the same file * are required at the same time, then the {@link * java.nio.file.Files#readAttributes(Path,Class,LinkOption[]) * Files.readAttributes} method may be used. * * @return The length, in bytes, of the file denoted by this abstract * pathname, or <code>0L</code> if the file does not exist. Some * operating systems may return <code>0L</code> for pathnames * denoting system-dependent entities such as devices or pipes. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method denies read access to the file */ public long length() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getLength(this); } /* -- File operations -- */ /** * Atomically creates a new, empty file named by this abstract pathname if * and only if a file with this name does not yet exist. The check for the * existence of the file and the creation of the file if it does not exist * are a single operation that is atomic with respect to all other * filesystem activities that might affect the file. * <P> * Note: this method should <i>not</i> be used for file-locking, as * the resulting protocol cannot be made to work reliably. The * {@link java.nio.channels.FileLock FileLock} * facility should be used instead. * * @return <code>true</code> if the named file does not exist and was * successfully created; <code>false</code> if the named file * already exists * * @throws IOException * If an I/O error occurred * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.2 */ public boolean createNewFile() throws IOException { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkWrite(path); if (isInvalid()) { throw new IOException("Invalid file path"); } return fs.createFileExclusively(path); } /** * Deletes the file or directory denoted by this abstract pathname. If * this pathname denotes a directory, then the directory must be empty in * order to be deleted. * * <p> Note that the {@link java.nio.file.Files} class defines the {@link * java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException} * when a file cannot be deleted. This is useful for error reporting and to * diagnose why a file cannot be deleted. * * @return <code>true</code> if and only if the file or directory is * successfully deleted; <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkDelete} method denies * delete access to the file */ public boolean delete() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return false; } return fs.delete(this); } /** * Requests that the file or directory denoted by this abstract * pathname be deleted when the virtual machine terminates. * Files (or directories) are deleted in the reverse order that * they are registered. Invoking this method to delete a file or * directory that is already registered for deletion has no effect. * Deletion will be attempted only for normal termination of the * virtual machine, as defined by the Java Language Specification. * * <p> Once deletion has been requested, it is not possible to cancel the * request. This method should therefore be used with care. * * <P> * Note: this method should <i>not</i> be used for file-locking, as * the resulting protocol cannot be made to work reliably. The * {@link java.nio.channels.FileLock FileLock} * facility should be used instead. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkDelete} method denies * delete access to the file * * @see #delete * * @since 1.2 */ public void deleteOnExit() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return; } DeleteOnExitHook.add(path); } /** * Returns an array of strings naming the files and directories in the * directory denoted by this abstract pathname. * * <p> If this abstract pathname does not denote a directory, then this * method returns {@code null}. Otherwise an array of strings is * returned, one for each file or directory in the directory. Names * denoting the directory itself and the directory's parent directory are * not included in the result. Each string is a file name rather than a * complete path. * * <p> There is no guarantee that the name strings in the resulting array * will appear in any specific order; they are not, in particular, * guaranteed to appear in alphabetical order. * * <p> Note that the {@link java.nio.file.Files} class defines the {@link * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to * open a directory and iterate over the names of the files in the directory. * This may use less resources when working with very large directories, and * may be more responsive when working with remote directories. * * @return An array of strings naming the files and directories in the * directory denoted by this abstract pathname. The array will be * empty if the directory is empty. Returns {@code null} if * this abstract pathname does not denote a directory, or if an * I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory */ public String[] list() { return normalizedList(); } /** * Returns an array of strings naming the files and directories in the * directory denoted by this abstract pathname. The strings are * ensured to represent normalized paths. * * @return An array of strings naming the files and directories in the * directory denoted by this abstract pathname. The array will be * empty if the directory is empty. Returns {@code null} if * this abstract pathname does not denote a directory, or if an * I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory */ private final String[] normalizedList() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return null; } String[] s = fs.list(this); if (s != null && getClass() != File.class) { String[] normalized = new String[s.length]; for (int i = 0; i < s.length; i++) { normalized[i] = fs.normalize(s[i]); } s = normalized; } return s; } /** * Returns an array of strings naming the files and directories in the * directory denoted by this abstract pathname that satisfy the specified * filter. The behavior of this method is the same as that of the * {@link #list()} method, except that the strings in the returned array * must satisfy the filter. If the given {@code filter} is {@code null} * then all names are accepted. Otherwise, a name satisfies the filter if * and only if the value {@code true} results when the {@link * FilenameFilter#accept FilenameFilter.accept(File,&nbsp;String)} method * of the filter is invoked on this abstract pathname and the name of a * file or directory in the directory that it denotes. * * @param filter * A filename filter * * @return An array of strings naming the files and directories in the * directory denoted by this abstract pathname that were accepted * by the given {@code filter}. The array will be empty if the * directory is empty or if no names were accepted by the filter. * Returns {@code null} if this abstract pathname does not denote * a directory, or if an I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory * * @see java.nio.file.Files#newDirectoryStream(Path,String) */ public String[] list(FilenameFilter filter) { String names[] = normalizedList(); if ((names == null) || (filter == null)) { return names; } List<String> v = new ArrayList<>(); for (int i = 0 ; i < names.length ; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } return v.toArray(new String[v.size()]); } /** * Returns an array of abstract pathnames denoting the files in the * directory denoted by this abstract pathname. * * <p> If this abstract pathname does not denote a directory, then this * method returns {@code null}. Otherwise an array of {@code File} objects * is returned, one for each file or directory in the directory. Pathnames * denoting the directory itself and the directory's parent directory are * not included in the result. Each resulting abstract pathname is * constructed from this abstract pathname using the {@link #File(File, * String) File(File,&nbsp;String)} constructor. Therefore if this * pathname is absolute then each resulting pathname is absolute; if this * pathname is relative then each resulting pathname will be relative to * the same directory. * * <p> There is no guarantee that the name strings in the resulting array * will appear in any specific order; they are not, in particular, * guaranteed to appear in alphabetical order. * * <p> Note that the {@link java.nio.file.Files} class defines the {@link * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method * to open a directory and iterate over the names of the files in the * directory. This may use less resources when working with very large * directories. * * @return An array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname. * The array will be empty if the directory is empty. Returns * {@code null} if this abstract pathname does not denote a * directory, or if an I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory * * @since 1.2 */ public File[] listFiles() { String[] ss = normalizedList(); if (ss == null) return null; int n = ss.length; File[] fs = new File[n]; for (int i = 0; i < n; i++) { fs[i] = new File(ss[i], this); } return fs; } /** * Returns an array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname that * satisfy the specified filter. The behavior of this method is the same * as that of the {@link #listFiles()} method, except that the pathnames in * the returned array must satisfy the filter. If the given {@code filter} * is {@code null} then all pathnames are accepted. Otherwise, a pathname * satisfies the filter if and only if the value {@code true} results when * the {@link FilenameFilter#accept * FilenameFilter.accept(File,&nbsp;String)} method of the filter is * invoked on this abstract pathname and the name of a file or directory in * the directory that it denotes. * * @param filter * A filename filter * * @return An array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname. * The array will be empty if the directory is empty. Returns * {@code null} if this abstract pathname does not denote a * directory, or if an I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory * * @since 1.2 * @see java.nio.file.Files#newDirectoryStream(Path,String) */ public File[] listFiles(FilenameFilter filter) { String ss[] = normalizedList(); if (ss == null) return null; ArrayList<File> files = new ArrayList<>(); for (String s : ss) if ((filter == null) || filter.accept(this, s)) files.add(new File(s, this)); return files.toArray(new File[files.size()]); } /** * Returns an array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname that * satisfy the specified filter. The behavior of this method is the same * as that of the {@link #listFiles()} method, except that the pathnames in * the returned array must satisfy the filter. If the given {@code filter} * is {@code null} then all pathnames are accepted. Otherwise, a pathname * satisfies the filter if and only if the value {@code true} results when * the {@link FileFilter#accept FileFilter.accept(File)} method of the * filter is invoked on the pathname. * * @param filter * A file filter * * @return An array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname. * The array will be empty if the directory is empty. Returns * {@code null} if this abstract pathname does not denote a * directory, or if an I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory * * @since 1.2 * @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter) */ public File[] listFiles(FileFilter filter) { String ss[] = normalizedList(); if (ss == null) return null; ArrayList<File> files = new ArrayList<>(); for (String s : ss) { File f = new File(s, this); if ((filter == null) || filter.accept(f)) files.add(f); } return files.toArray(new File[files.size()]); } /** * Creates the directory named by this abstract pathname. * * @return <code>true</code> if and only if the directory was * created; <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not permit the named directory to be created */ public boolean mkdir() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.createDirectory(this); } /** * Creates the directory named by this abstract pathname, including any * necessary but nonexistent parent directories. Note that if this * operation fails it may have succeeded in creating some of the necessary * parent directories. * * @return <code>true</code> if and only if the directory was created, * along with all necessary parent directories; <code>false</code> * otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method does not permit verification of the existence of the * named directory and all necessary parent directories; or if * the {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not permit the named directory and all necessary * parent directories to be created */ public boolean mkdirs() { if (exists()) { return false; } if (mkdir()) { return true; } File canonFile = null; try { canonFile = getCanonicalFile(); } catch (IOException e) { return false; } File parent = canonFile.getParentFile(); return (parent != null && (parent.mkdirs() || parent.exists()) && canonFile.mkdir()); } /** * Renames the file denoted by this abstract pathname. * * <p> Many aspects of the behavior of this method are inherently * platform-dependent: The rename operation might not be able to move a * file from one filesystem to another, it might not be atomic, and it * might not succeed if a file with the destination abstract pathname * already exists. The return value should always be checked to make sure * that the rename operation was successful. * * <p> Note that the {@link java.nio.file.Files} class defines the {@link * java.nio.file.Files#move move} method to move or rename a file in a * platform independent manner. * * @param dest The new abstract pathname for the named file * * @return <code>true</code> if and only if the renaming succeeded; * <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to either the old or new pathnames * * @throws NullPointerException * If parameter <code>dest</code> is <code>null</code> */ public boolean renameTo(File dest) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); security.checkWrite(dest.path); } if (dest == null) { throw new NullPointerException(); } if (this.isInvalid() || dest.isInvalid()) { return false; } return fs.rename(this, dest); } /** * Sets the last-modified time of the file or directory named by this * abstract pathname. * * <p> All platforms support file-modification times to the nearest second, * but some provide more precision. The argument will be truncated to fit * the supported precision. If the operation succeeds and no intervening * operations on the file take place, then the next invocation of the * {@link #lastModified} method will return the (possibly * truncated) <code>time</code> argument that was passed to this method. * * @param time The new last-modified time, measured in milliseconds since * the epoch (00:00:00 GMT, January 1, 1970) * * @return <code>true</code> if and only if the operation succeeded; * <code>false</code> otherwise * * @throws IllegalArgumentException If the argument is negative * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the named file * * @since 1.2 */ public boolean setLastModified(long time) { if (time < 0) throw new IllegalArgumentException("Negative time"); SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setLastModifiedTime(this, time); } /** * Marks the file or directory named by this abstract pathname so that * only read operations are allowed. After invoking this method the file * or directory will not change until it is either deleted or marked * to allow write access. On some platforms it may be possible to start the * Java virtual machine with special privileges that allow it to modify * files that are marked read-only. Whether or not a read-only file or * directory may be deleted depends upon the underlying system. * * @return <code>true</code> if and only if the operation succeeded; * <code>false</code> otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the named file * * @since 1.2 */ public boolean setReadOnly() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setReadOnly(this); } /** * Sets the owner's or everybody's write permission for this abstract * pathname. On some platforms it may be possible to start the Java virtual * machine with special privileges that allow it to modify files that * disallow write operations. * * <p> The {@link java.nio.file.Files} class defines methods that operate on * file attributes including file permissions. This may be used when finer * manipulation of file permissions is required. * * @param writable * If <code>true</code>, sets the access permission to allow write * operations; if <code>false</code> to disallow write operations * * @param ownerOnly * If <code>true</code>, the write permission applies only to the * owner's write permission; otherwise, it applies to everybody. If * the underlying file system can not distinguish the owner's write * permission from that of others, then the permission will apply to * everybody, regardless of this value. * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to change * the access permissions of this abstract pathname. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the named file * * @since 1.6 */ public boolean setWritable(boolean writable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly); } /** * A convenience method to set the owner's write permission for this abstract * pathname. On some platforms it may be possible to start the Java virtual * machine with special privileges that allow it to modify files that * disallow write operations. * * <p> An invocation of this method of the form {@code file.setWritable(arg)} * behaves in exactly the same way as the invocation * * <pre>{@code * file.setWritable(arg, true) * }</pre> * * @param writable * If <code>true</code>, sets the access permission to allow write * operations; if <code>false</code> to disallow write operations * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to * change the access permissions of this abstract pathname. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.6 */ public boolean setWritable(boolean writable) { return setWritable(writable, true); } /** * Sets the owner's or everybody's read permission for this abstract * pathname. On some platforms it may be possible to start the Java virtual * machine with special privileges that allow it to read files that are * marked as unreadable. * * <p> The {@link java.nio.file.Files} class defines methods that operate on * file attributes including file permissions. This may be used when finer * manipulation of file permissions is required. * * @param readable * If <code>true</code>, sets the access permission to allow read * operations; if <code>false</code> to disallow read operations * * @param ownerOnly * If <code>true</code>, the read permission applies only to the * owner's read permission; otherwise, it applies to everybody. If * the underlying file system can not distinguish the owner's read * permission from that of others, then the permission will apply to * everybody, regardless of this value. * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to * change the access permissions of this abstract pathname. If * <code>readable</code> is <code>false</code> and the underlying * file system does not implement a read permission, then the * operation will fail. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.6 */ public boolean setReadable(boolean readable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly); } /** * A convenience method to set the owner's read permission for this abstract * pathname. On some platforms it may be possible to start the Java virtual * machine with special privileges that allow it to read files that are * marked as unreadable. * * <p>An invocation of this method of the form {@code file.setReadable(arg)} * behaves in exactly the same way as the invocation * * <pre>{@code * file.setReadable(arg, true) * }</pre> * * @param readable * If <code>true</code>, sets the access permission to allow read * operations; if <code>false</code> to disallow read operations * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to * change the access permissions of this abstract pathname. If * <code>readable</code> is <code>false</code> and the underlying * file system does not implement a read permission, then the * operation will fail. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.6 */ public boolean setReadable(boolean readable) { return setReadable(readable, true); } /** * Sets the owner's or everybody's execute permission for this abstract * pathname. On some platforms it may be possible to start the Java virtual * machine with special privileges that allow it to execute files that are * not marked executable. * * <p> The {@link java.nio.file.Files} class defines methods that operate on * file attributes including file permissions. This may be used when finer * manipulation of file permissions is required. * * @param executable * If <code>true</code>, sets the access permission to allow execute * operations; if <code>false</code> to disallow execute operations * * @param ownerOnly * If <code>true</code>, the execute permission applies only to the * owner's execute permission; otherwise, it applies to everybody. * If the underlying file system can not distinguish the owner's * execute permission from that of others, then the permission will * apply to everybody, regardless of this value. * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to * change the access permissions of this abstract pathname. If * <code>executable</code> is <code>false</code> and the underlying * file system does not implement an execute permission, then the * operation will fail. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.6 */ public boolean setExecutable(boolean executable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly); } /** * A convenience method to set the owner's execute permission for this * abstract pathname. On some platforms it may be possible to start the Java * virtual machine with special privileges that allow it to execute files * that are not marked executable. * * <p>An invocation of this method of the form {@code file.setExcutable(arg)} * behaves in exactly the same way as the invocation * * <pre>{@code * file.setExecutable(arg, true) * }</pre> * * @param executable * If <code>true</code>, sets the access permission to allow execute * operations; if <code>false</code> to disallow execute operations * * @return <code>true</code> if and only if the operation succeeded. The * operation will fail if the user does not have permission to * change the access permissions of this abstract pathname. If * <code>executable</code> is <code>false</code> and the underlying * file system does not implement an execute permission, then the * operation will fail. * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the file * * @since 1.6 */ public boolean setExecutable(boolean executable) { return setExecutable(executable, true); } /** * Tests whether the application can execute the file denoted by this * abstract pathname. On some platforms it may be possible to start the * Java virtual machine with special privileges that allow it to execute * files that are not marked executable. Consequently this method may return * {@code true} even though the file does not have execute permissions. * * @return <code>true</code> if and only if the abstract pathname exists * <em>and</em> the application is allowed to execute the file * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkExec(java.lang.String)} * method denies execute access to the file * * @since 1.6 */ public boolean canExecute() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExec(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE); } /* -- Filesystem interface -- */ /** * List the available filesystem roots. * * <p> A particular Java platform may support zero or more * hierarchically-organized file systems. Each file system has a * {@code root} directory from which all other files in that file system * can be reached. Windows platforms, for example, have a root directory * for each active drive; UNIX platforms have a single root directory, * namely {@code "/"}. The set of available filesystem roots is affected * by various system-level operations such as the insertion or ejection of * removable media and the disconnecting or unmounting of physical or * virtual disk drives. * * <p> This method returns an array of {@code File} objects that denote the * root directories of the available filesystem roots. It is guaranteed * that the canonical pathname of any file physically present on the local * machine will begin with one of the roots returned by this method. * * <p> The canonical pathname of a file that resides on some other machine * and is accessed via a remote-filesystem protocol such as SMB or NFS may * or may not begin with one of the roots returned by this method. If the * pathname of a remote file is syntactically indistinguishable from the * pathname of a local file then it will begin with one of the roots * returned by this method. Thus, for example, {@code File} objects * denoting the root directories of the mapped network drives of a Windows * platform will be returned by this method, while {@code File} objects * containing UNC pathnames will not be returned by this method. * * <p> Unlike most methods in this class, this method does not throw * security exceptions. If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to a * particular root directory, then that directory will not appear in the * result. * * @return An array of {@code File} objects denoting the available * filesystem roots, or {@code null} if the set of roots could not * be determined. The array will be empty if there are no * filesystem roots. * * @since 1.2 * @see java.nio.file.FileStore */ public static File[] listRoots() { return fs.listRoots(); } /* -- Disk usage -- */ /** * Returns the size of the partition <a href="#partName">named</a> by this * abstract pathname. * * @return The size, in bytes, of the partition or {@code 0L} if this * abstract pathname does not name a partition * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}{@code ("getFileSystemAttributes")} * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getTotalSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_TOTAL); } /** * Returns the number of unallocated bytes in the partition <a * href="#partName">named</a> by this abstract path name. * * <p> The returned number of unallocated bytes is a hint, but not * a guarantee, that it is possible to use most or any of these * bytes. The number of unallocated bytes is most likely to be * accurate immediately after this call. It is likely to be made * inaccurate by any external I/O operations including those made * on the system outside of this virtual machine. This method * makes no guarantee that write operations to this file system * will succeed. * * @return The number of unallocated bytes on the partition or {@code 0L} * if the abstract pathname does not name a partition. This * value will be less than or equal to the total file system size * returned by {@link #getTotalSpace}. * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}{@code ("getFileSystemAttributes")} * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getFreeSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_FREE); } /** * Returns the number of bytes available to this virtual machine on the * partition <a href="#partName">named</a> by this abstract pathname. When * possible, this method checks for write permissions and other operating * system restrictions and will therefore usually provide a more accurate * estimate of how much new data can actually be written than {@link * #getFreeSpace}. * * <p> The returned number of available bytes is a hint, but not a * guarantee, that it is possible to use most or any of these bytes. The * number of unallocated bytes is most likely to be accurate immediately * after this call. It is likely to be made inaccurate by any external * I/O operations including those made on the system outside of this * virtual machine. This method makes no guarantee that write operations * to this file system will succeed. * * @return The number of available bytes on the partition or {@code 0L} * if the abstract pathname does not name a partition. On * systems where this information is not available, this method * will be equivalent to a call to {@link #getFreeSpace}. * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}{@code ("getFileSystemAttributes")} * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getUsableSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_USABLE); } /* -- Temporary files -- */ private static class TempDirectory { private TempDirectory() { } // temporary directory location private static final File tmpdir = new File( GetPropertyAction.privilegedGetProperty("java.io.tmpdir")); static File location() { return tmpdir; } // file name generation private static final SecureRandom random = new SecureRandom(); private static int shortenSubName(int subNameLength, int excess, int nameMin) { int newLength = Math.max(nameMin, subNameLength - excess); if (newLength < subNameLength) { return newLength; } return subNameLength; } static File generateFile(String prefix, String suffix, File dir) throws IOException { long n = random.nextLong(); String nus = Long.toUnsignedString(n); // Use only the file name from the supplied prefix prefix = (new File(prefix)).getName(); int prefixLength = prefix.length(); int nusLength = nus.length(); int suffixLength = suffix.length();; String name; int nameMax = fs.getNameMax(dir.getPath()); int excess = prefixLength + nusLength + suffixLength - nameMax; if (excess <= 0) { name = prefix + nus + suffix; } else { // Name exceeds the maximum path component length: shorten it // Attempt to shorten the prefix length to no less then 3 prefixLength = shortenSubName(prefixLength, excess, 3); excess = prefixLength + nusLength + suffixLength - nameMax; if (excess > 0) { // Attempt to shorten the suffix length to no less than // 0 or 4 depending on whether it begins with a dot ('.') suffixLength = shortenSubName(suffixLength, excess, suffix.indexOf(".") == 0 ? 4 : 0); suffixLength = shortenSubName(suffixLength, excess, 3); excess = prefixLength + nusLength + suffixLength - nameMax; } if (excess > 0 && excess <= nusLength - 5) { // Attempt to shorten the random character string length // to no less than 5 nusLength = shortenSubName(nusLength, excess, 5); } StringBuilder sb = new StringBuilder(prefixLength + nusLength + suffixLength); sb.append(prefixLength < prefix.length() ? prefix.substring(0, prefixLength) : prefix); sb.append(nusLength < nus.length() ? nus.substring(0, nusLength) : nus); sb.append(suffixLength < suffix.length() ? suffix.substring(0, suffixLength) : suffix); name = sb.toString(); } // Normalize the path component name = fs.normalize(name); File f = new File(dir, name); if (!name.equals(f.getName()) || f.isInvalid()) { if (System.getSecurityManager() != null) throw new IOException("Unable to create temporary file"); else throw new IOException("Unable to create temporary file, " + name); } return f; } } /** * <p> Creates a new empty file in the specified directory, using the * given prefix and suffix strings to generate its name. If this method * returns successfully then it is guaranteed that: * * <ol> * <li> The file denoted by the returned abstract pathname did not exist * before this method was invoked, and * <li> Neither this method nor any of its variants will return the same * abstract pathname again in the current invocation of the virtual * machine. * </ol> * * This method provides only part of a temporary-file facility. To arrange * for a file created by this method to be deleted automatically, use the * {@link #deleteOnExit} method. * * <p> The <code>prefix</code> argument must be at least three characters * long. It is recommended that the prefix be a short, meaningful string * such as <code>"hjb"</code> or <code>"mail"</code>. The * <code>suffix</code> argument may be <code>null</code>, in which case the * suffix <code>".tmp"</code> will be used. * * <p> To create the new file, the prefix and the suffix may first be * adjusted to fit the limitations of the underlying platform. If the * prefix is too long then it will be truncated, but its first three * characters will always be preserved. If the suffix is too long then it * too will be truncated, but if it begins with a period character * (<code>'.'</code>) then the period and the first three characters * following it will always be preserved. Once these adjustments have been * made the name of the new file will be generated by concatenating the * prefix, five or more internally-generated characters, and the suffix. * * <p> If the <code>directory</code> argument is <code>null</code> then the * system-dependent default temporary-file directory will be used. The * default temporary-file directory is specified by the system property * <code>java.io.tmpdir</code>. On UNIX systems the default value of this * property is typically <code>"/tmp"</code> or <code>"/var/tmp"</code>; on * Microsoft Windows systems it is typically <code>"C:\\WINNT\\TEMP"</code>. A different * value may be given to this system property when the Java virtual machine * is invoked, but programmatic changes to this property are not guaranteed * to have any effect upon the temporary directory used by this method. * * @param prefix The prefix string to be used in generating the file's * name; must be at least three characters long * * @param suffix The suffix string to be used in generating the file's * name; may be <code>null</code>, in which case the * suffix <code>".tmp"</code> will be used * * @param directory The directory in which the file is to be created, or * <code>null</code> if the default temporary-file * directory is to be used * * @return An abstract pathname denoting a newly-created empty file * * @throws IllegalArgumentException * If the <code>prefix</code> argument contains fewer than three * characters * * @throws IOException If a file could not be created * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not allow a file to be created * * @since 1.2 */ public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (prefix.length() < 3) { throw new IllegalArgumentException("Prefix string \"" + prefix + "\" too short: length must be at least 3"); } if (suffix == null) suffix = ".tmp"; File tmpdir = (directory != null) ? directory : TempDirectory.location(); SecurityManager sm = System.getSecurityManager(); File f; do { f = TempDirectory.generateFile(prefix, suffix, tmpdir); if (sm != null) { try { sm.checkWrite(f.getPath()); } catch (SecurityException se) { // don't reveal temporary directory location if (directory == null) throw new SecurityException("Unable to create temporary file"); throw se; } } } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); if (!fs.createFileExclusively(f.getPath())) throw new IOException("Unable to create temporary file"); return f; } /** * Creates an empty file in the default temporary-file directory, using * the given prefix and suffix to generate its name. Invoking this method * is equivalent to invoking {@link #createTempFile(java.lang.String, * java.lang.String, java.io.File) * createTempFile(prefix,&nbsp;suffix,&nbsp;null)}. * * <p> The {@link * java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[]) * Files.createTempFile} method provides an alternative method to create an * empty file in the temporary-file directory. Files created by that method * may have more restrictive access permissions to files created by this * method and so may be more suited to security-sensitive applications. * * @param prefix The prefix string to be used in generating the file's * name; must be at least three characters long * * @param suffix The suffix string to be used in generating the file's * name; may be <code>null</code>, in which case the * suffix <code>".tmp"</code> will be used * * @return An abstract pathname denoting a newly-created empty file * * @throws IllegalArgumentException * If the <code>prefix</code> argument contains fewer than three * characters * * @throws IOException If a file could not be created * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not allow a file to be created * * @since 1.2 * @see java.nio.file.Files#createTempDirectory(String,FileAttribute[]) */ public static File createTempFile(String prefix, String suffix) throws IOException { return createTempFile(prefix, suffix, null); } /* -- Basic infrastructure -- */ /** * Compares two abstract pathnames lexicographically. The ordering * defined by this method depends upon the underlying system. On UNIX * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows * systems it is not. * * @param pathname The abstract pathname to be compared to this abstract * pathname * * @return Zero if the argument is equal to this abstract pathname, a * value less than zero if this abstract pathname is * lexicographically less than the argument, or a value greater * than zero if this abstract pathname is lexicographically * greater than the argument * * @since 1.2 */ public int compareTo(File pathname) { return fs.compare(this, pathname); } /** * Tests this abstract pathname for equality with the given object. * Returns <code>true</code> if and only if the argument is not * <code>null</code> and is an abstract pathname that denotes the same file * or directory as this abstract pathname. Whether or not two abstract * pathnames are equal depends upon the underlying system. On UNIX * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows * systems it is not. * * @param obj The object to be compared with this abstract pathname * * @return <code>true</code> if and only if the objects are the same; * <code>false</code> otherwise */ public boolean equals(Object obj) { if ((obj != null) && (obj instanceof File)) { return compareTo((File)obj) == 0; } return false; } /** * Computes a hash code for this abstract pathname. Because equality of * abstract pathnames is inherently system-dependent, so is the computation * of their hash codes. On UNIX systems, the hash code of an abstract * pathname is equal to the exclusive <em>or</em> of the hash code * of its pathname string and the decimal value * <code>1234321</code>. On Microsoft Windows systems, the hash * code is equal to the exclusive <em>or</em> of the hash code of * its pathname string converted to lower case and the decimal * value <code>1234321</code>. Locale is not taken into account on * lowercasing the pathname string. * * @return A hash code for this abstract pathname */ public int hashCode() { return fs.hashCode(this); } /** * Returns the pathname string of this abstract pathname. This is just the * string returned by the {@link #getPath} method. * * @return The string form of this abstract pathname */ public String toString() { return getPath(); } /** * WriteObject is called to save this filename. * The separator character is saved also so it can be replaced * in case the path is reconstituted on a different host type. * * @serialData Default fields followed by separator character. */ private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeChar(separatorChar); // Add the separator character } /** * readObject is called to restore this filename. * The original separator character is read. If it is different * than the separator character on this system, then the old separator * is replaced by the local separator. */ private synchronized void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = s.readFields(); String pathField = (String)fields.get("path", null); char sep = s.readChar(); // read the previous separator char if (sep != separatorChar) pathField = pathField.replace(sep, separatorChar); String path = fs.normalize(pathField); UNSAFE.putObject(this, PATH_OFFSET, path); UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path)); } private static final jdk.internal.misc.Unsafe UNSAFE = jdk.internal.misc.Unsafe.getUnsafe(); private static final long PATH_OFFSET = UNSAFE.objectFieldOffset(File.class, "path"); private static final long PREFIX_LENGTH_OFFSET = UNSAFE.objectFieldOffset(File.class, "prefixLength"); /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 301077366599181567L; // -- Integration with java.nio.file -- private transient volatile Path filePath; /** * Returns a {@link Path java.nio.file.Path} object constructed from * this abstract path. The resulting {@code Path} is associated with the * {@link java.nio.file.FileSystems#getDefault default-filesystem}. * * <p> The first invocation of this method works as if invoking it were * equivalent to evaluating the expression: * <blockquote><pre> * {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link * java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}()); * </pre></blockquote> * Subsequent invocations of this method return the same {@code Path}. * * <p> If this abstract pathname is the empty abstract pathname then this * method returns a {@code Path} that may be used to access the current * user directory. * * @return a {@code Path} constructed from this abstract path * * @throws java.nio.file.InvalidPathException * if a {@code Path} object cannot be constructed from the abstract * path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath}) * * @since 1.7 * @see Path#toFile */ public Path toPath() { Path result = filePath; if (result == null) { synchronized (this) { result = filePath; if (result == null) { result = FileSystems.getDefault().getPath(path); filePath = result; } } } return result; } }
package io.bitrise.trace.scheduler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import android.content.Context; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.Mockito; /** * Unit tests for {@link Scheduler}. */ public class SchedulerTest { final Context mockContext = Mockito.mock(Context.class); final Runnable mockRunnable = Mockito.mock(Runnable.class); final ExecutorScheduler scheduler = new ExecutorScheduler(mockContext, mockRunnable); @Test public void schedule() { final Integer id = scheduler.schedule(); assertEquals(new Integer(-1), id); assertNotNull(scheduler.scheduledFuture); assertTrue(scheduler.scheduledFuture.getDelay(TimeUnit.MILLISECONDS) <= 0); // delay might have already elapsed, which makes the delay negative } @Test public void scheduleDelayed() { final Integer id = scheduler.scheduleDelayed(); assertEquals(new Integer(-1), id); assertNotNull(scheduler.scheduledFuture); assertTrue(scheduler.scheduledFuture.getDelay(TimeUnit.MILLISECONDS) > (Scheduler.DEFAULT_SCHEDULE_INITIAL_DELAY_MS - 100)); // we cannot get the delay immediately, several milliseconds may have passed. } @Test public void calculateDelay_inFuture() { final long delay = scheduler.calculateDelay(System.currentTimeMillis() + 100); assertTrue(delay > 0); } @Test public void calculateDelay_timePassed() { final long delay = scheduler.calculateDelay(System.currentTimeMillis() - 100); assertEquals(0, delay); } }
package nextstep.subway.error.exception; public class CannotRemoveStateException extends BusinessException { public CannotRemoveStateException(Long id) { super(makeMessage(id), ErrorCode.CANNOT_REMOVE_STATE); } private static String makeMessage(Long id) { return id + ErrorCode.CANNOT_REMOVE_STATE.getMessage(); } }
package java.android.quanlybanhang.login; import android.app.Activity; import android.app.AlertDialog; import android.view.LayoutInflater; import java.android.quanlybanhang.R; public class LoadingDialog { private Activity activity; private AlertDialog dialog; LoadingDialog(Activity myActivity){ activity = myActivity; } void startLoadingDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(activity); LayoutInflater inflater = activity.getLayoutInflater(); builder.setView(inflater.inflate(R.layout.custom_loading, null)); builder.setCancelable(false); dialog = builder.create(); dialog.show(); } void dismissDialog(){ dialog.dismiss(); } }
public class QuickFindUF { private int[] id; //Default constructor public QuickFindUF(int N) { id = new int[N]; //init the array of N size for (int i = 0; i < N; i++) { id[i] = i; //set id of each object to itself } } public boolean connected(int p, int q) { return id[p] == id[q]; } public void union(int p, int q) { int pid = id[p]; int qid = id[q]; for (int i = 0; i < id.length(); i++) { if (id[i] == pid) id[i] = qid; } } }
package com.antonkesy.udptool.udp; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.LinkedList; import java.util.Objects; import java.util.Queue; public class UDPSendReceive implements Runnable { private boolean isRunning = true; private final int localPort; private final int remotePort; private final InetAddress remoteAddress; private final boolean isTimeoutEnabled; private final int timeoutTime; private final int bufferSize; private final int listenInterval; private final boolean isListening; private final boolean isListeningInterval; private final ISocketResponses socketResponseHandler; private DatagramSocket udpSocket; byte[] buffer; DatagramPacket packet; private final Queue<byte[]> messageQue = new LinkedList<>(); public UDPSendReceive(int localPort, int remotePort, InetAddress remoteAddress, boolean isTimeoutEnabled, int timeoutTime, int bufferSize, int listenInterval, boolean isListening, boolean isListeningInterval, ISocketResponses socketResponseHandler) { this.localPort = localPort; this.remotePort = remotePort; this.remoteAddress = remoteAddress; this.isTimeoutEnabled = isTimeoutEnabled; this.timeoutTime = timeoutTime; this.bufferSize = bufferSize; this.listenInterval = listenInterval; this.isListening = isListening; this.isListeningInterval = isListeningInterval; this.socketResponseHandler = socketResponseHandler; } @Override public void run() { try { if (udpSocket != null) { udpSocket.close(); } udpSocket = new DatagramSocket(localPort); socketResponseHandler.socketStart(); buffer = new byte[bufferSize]; packet = new DatagramPacket(buffer, buffer.length, remoteAddress, remotePort); while (isRunning) { if (messageQue.size() > 0) { sendNextMessage(); } try { listenForMessages(); } catch (SocketTimeoutException e) { socketResponseHandler.socketTimeOut(TimeOutReason.RECEIVE_TIMEOUT); } catch (IOException e) { isRunning = false; udpSocket.close(); socketResponseHandler.ioException(Objects.requireNonNull(e.getMessage())); socketResponseHandler.socketClosed(); } } } catch (SocketException e) { socketResponseHandler.socketException(Objects.requireNonNull(e.getMessage())); } } private void sendNextMessage() { byte[] nextMessageContent = messageQue.poll(); assert nextMessageContent != null; DatagramPacket packet = new DatagramPacket(nextMessageContent, nextMessageContent.length, remoteAddress, remotePort); try { udpSocket.send(packet); socketResponseHandler.sendPacket(packet.getData()); if (isTimeoutEnabled) { udpSocket.setSoTimeout(timeoutTime); udpSocket.receive(packet); socketResponseHandler.dataReceived(packet.getData()); } } catch (SocketTimeoutException e) { socketResponseHandler.socketTimeOut(TimeOutReason.SEND_RESPONSE_TIMEOUT); } catch (IOException e) { socketResponseHandler.ioException(Objects.requireNonNull(e.getMessage())); } } private void listenForMessages() throws IOException { if (isListening) { if (isListeningInterval) { udpSocket.setSoTimeout(listenInterval); } udpSocket.receive(packet); socketResponseHandler.dataReceived(packet.getData()); } } public void kill() { if (udpSocket != null) { udpSocket.close(); } messageQue.clear(); isRunning = false; } public void addMessageToQue(@NotNull byte[] newMessage) { messageQue.add(newMessage); } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.updater; import com.intellij.concurrency.JobScheduler; import com.intellij.ide.ApplicationInitializedListener; import com.intellij.ide.StatisticsNotificationManager; import com.intellij.internal.statistic.connect.StatisticsService; import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerKt; import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider; import com.intellij.internal.statistic.eventLog.validator.SensitiveDataValidator; import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger; import com.intellij.internal.statistic.service.fus.collectors.FUStatisticsPersistence; import com.intellij.internal.statistic.service.fus.collectors.LegacyFUSProjectUsageTrigger; import com.intellij.internal.statistic.utils.StatisticsUploadAssistant; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.extensions.ExtensionNotApplicableException; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; final class StatisticsJobsScheduler implements ApplicationInitializedListener { private static final int SEND_STATISTICS_INITIAL_DELAY_IN_MILLIS = 5 * 60 * 1000; private static final int CHECK_STATISTICS_PROVIDERS_DELAY_IN_MIN = 1; public static final int LOG_APPLICATION_STATES_INITIAL_DELAY_IN_MIN = 15; public static final int LOG_APPLICATION_STATES_DELAY_IN_MIN = 24 * 60; public static final int LOG_PROJECTS_STATES_INITIAL_DELAY_IN_MIN = 30; public static final int LOG_PROJECTS_STATES_DELAY_IN_MIN = 12 * 60; private static final Map<Project, Future<?>> myPersistStatisticsSessionsMap = Collections.synchronizedMap(new HashMap<>()); StatisticsJobsScheduler() { if (ApplicationManager.getApplication().isUnitTestMode()) { throw ExtensionNotApplicableException.INSTANCE; } } @Override public void componentsInitialized() { final StatisticsNotificationManager notificationManager = ServiceManager.getService(StatisticsNotificationManager.class); if (notificationManager != null) { notificationManager.showNotificationIfNeeded(); } runEventLogStatisticsService(); runStatesLogging(); runLegacyDataCleanupService(); runWhitelistStorageUpdater(); } private static void runWhitelistStorageUpdater() { JobScheduler.getScheduler().scheduleWithFixedDelay( () -> { final List<StatisticsEventLoggerProvider> providers = StatisticsEventLoggerKt.getEventLogProviders(); for (StatisticsEventLoggerProvider provider : providers) { if (provider.isRecordEnabled()) { SensitiveDataValidator.getInstance(provider.getRecorderId()).update(); } } }, 3, 180, TimeUnit.MINUTES); } private static void runEventLogStatisticsService() { JobScheduler.getScheduler().schedule(() -> { final List<StatisticsEventLoggerProvider> providers = StatisticsEventLoggerKt.getEventLogProviders(); for (StatisticsEventLoggerProvider provider : providers) { if (provider.isSendEnabled()) { final StatisticsService statisticsService = StatisticsUploadAssistant.getEventLogStatisticsService(provider.getRecorderId()); runStatisticsServiceWithDelay(statisticsService, provider.getSendFrequencyMs()); } } }, CHECK_STATISTICS_PROVIDERS_DELAY_IN_MIN, TimeUnit.MINUTES); } private static void runStatesLogging() { if (!StatisticsUploadAssistant.isSendAllowed()) return; JobScheduler.getScheduler().scheduleWithFixedDelay(() -> FUStateUsagesLogger.create().logApplicationStates(), LOG_APPLICATION_STATES_INITIAL_DELAY_IN_MIN, LOG_APPLICATION_STATES_DELAY_IN_MIN, TimeUnit.MINUTES); MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectOpened(@NotNull Project project) { ScheduledFuture<?> future = JobScheduler.getScheduler().scheduleWithFixedDelay( () -> FUStateUsagesLogger.create().logProjectStates(project, new EmptyProgressIndicator()), LOG_PROJECTS_STATES_INITIAL_DELAY_IN_MIN, LOG_PROJECTS_STATES_DELAY_IN_MIN, TimeUnit.MINUTES); myPersistStatisticsSessionsMap.put(project, future); LegacyFUSProjectUsageTrigger.cleanup(project); } @Override public void projectClosed(@NotNull Project project) { Future<?> future = myPersistStatisticsSessionsMap.remove(project); if (future != null) { future.cancel(true); } } }); } private static void runLegacyDataCleanupService() { JobScheduler.getScheduler().schedule(() -> { FUStatisticsPersistence.clearLegacyStates(); }, 1, TimeUnit.MINUTES); } private static void runStatisticsServiceWithDelay(@NotNull final StatisticsService statisticsService, long delayInMs) { JobScheduler.getScheduler().scheduleWithFixedDelay( statisticsService::send, SEND_STATISTICS_INITIAL_DELAY_IN_MILLIS, delayInMs, TimeUnit.MILLISECONDS ); } }
package io.reactivex.internal.operators.flowable; import io.reactivex.Flowable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.MissingBackpressureException; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.internal.subscribers.QueueDrainSubscriber; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.NotificationLite; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.UnicastProcessor; import io.reactivex.subscribers.DisposableSubscriber; import io.reactivex.subscribers.SerializedSubscriber; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import kotlin.jvm.internal.LongCompanionObject; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; public final class FlowableWindowBoundarySelector<T, B, V> extends AbstractFlowableWithUpstream<T, Flowable<T>> { final int bufferSize; final Function<? super B, ? extends Publisher<V>> close; final Publisher<B> open; public FlowableWindowBoundarySelector(Flowable<T> flowable, Publisher<B> publisher, Function<? super B, ? extends Publisher<V>> function, int i) { super(flowable); this.open = publisher; this.close = function; this.bufferSize = i; } /* access modifiers changed from: protected */ public void subscribeActual(Subscriber<? super Flowable<T>> subscriber) { this.source.subscribe(new WindowBoundaryMainSubscriber(new SerializedSubscriber(subscriber), this.open, this.close, this.bufferSize)); } static final class WindowBoundaryMainSubscriber<T, B, V> extends QueueDrainSubscriber<T, Object, Flowable<T>> implements Subscription { final AtomicReference<Disposable> boundary = new AtomicReference<>(); final int bufferSize; final Function<? super B, ? extends Publisher<V>> close; final Publisher<B> open; final CompositeDisposable resources; Subscription upstream; final AtomicLong windows = new AtomicLong(); final List<UnicastProcessor<T>> ws; public boolean accept(Subscriber<? super Flowable<T>> subscriber, Object obj) { return false; } WindowBoundaryMainSubscriber(Subscriber<? super Flowable<T>> subscriber, Publisher<B> publisher, Function<? super B, ? extends Publisher<V>> function, int i) { super(subscriber, new MpscLinkedQueue()); this.open = publisher; this.close = function; this.bufferSize = i; this.resources = new CompositeDisposable(); this.ws = new ArrayList(); this.windows.lazySet(1); } public void onSubscribe(Subscription subscription) { if (SubscriptionHelper.validate(this.upstream, subscription)) { this.upstream = subscription; this.downstream.onSubscribe(this); if (!this.cancelled) { OperatorWindowBoundaryOpenSubscriber operatorWindowBoundaryOpenSubscriber = new OperatorWindowBoundaryOpenSubscriber(this); if (this.boundary.compareAndSet((Object) null, operatorWindowBoundaryOpenSubscriber)) { this.windows.getAndIncrement(); subscription.request(LongCompanionObject.MAX_VALUE); this.open.subscribe(operatorWindowBoundaryOpenSubscriber); } } } } public void onNext(T t) { if (!this.done) { if (fastEnter()) { for (UnicastProcessor<T> onNext : this.ws) { onNext.onNext(t); } if (leave(-1) == 0) { return; } } else { this.queue.offer(NotificationLite.next(t)); if (!enter()) { return; } } drainLoop(); } } public void onError(Throwable th) { if (this.done) { RxJavaPlugins.onError(th); return; } this.error = th; this.done = true; if (enter()) { drainLoop(); } if (this.windows.decrementAndGet() == 0) { this.resources.dispose(); } this.downstream.onError(th); } public void onComplete() { if (!this.done) { this.done = true; if (enter()) { drainLoop(); } if (this.windows.decrementAndGet() == 0) { this.resources.dispose(); } this.downstream.onComplete(); } } /* access modifiers changed from: package-private */ public void error(Throwable th) { this.upstream.cancel(); this.resources.dispose(); DisposableHelper.dispose(this.boundary); this.downstream.onError(th); } public void request(long j) { requested(j); } public void cancel() { this.cancelled = true; } /* access modifiers changed from: package-private */ public void dispose() { this.resources.dispose(); DisposableHelper.dispose(this.boundary); } /* access modifiers changed from: package-private */ public void drainLoop() { SimplePlainQueue simplePlainQueue = this.queue; Subscriber subscriber = this.downstream; List<UnicastProcessor<T>> list = this.ws; int i = 1; while (true) { boolean z = this.done; Object poll = simplePlainQueue.poll(); boolean z2 = poll == null; if (z && z2) { dispose(); Throwable th = this.error; if (th != null) { for (UnicastProcessor<T> onError : list) { onError.onError(th); } } else { for (UnicastProcessor<T> onComplete : list) { onComplete.onComplete(); } } list.clear(); return; } else if (z2) { i = leave(-i); if (i == 0) { return; } } else if (poll instanceof WindowOperation) { WindowOperation windowOperation = (WindowOperation) poll; if (windowOperation.w != null) { if (list.remove(windowOperation.w)) { windowOperation.w.onComplete(); if (this.windows.decrementAndGet() == 0) { dispose(); return; } } else { continue; } } else if (!this.cancelled) { UnicastProcessor create = UnicastProcessor.create(this.bufferSize); long requested = requested(); if (requested != 0) { list.add(create); subscriber.onNext(create); if (requested != LongCompanionObject.MAX_VALUE) { produced(1); } try { Publisher publisher = (Publisher) ObjectHelper.requireNonNull(this.close.apply(windowOperation.open), "The publisher supplied is null"); OperatorWindowBoundaryCloseSubscriber operatorWindowBoundaryCloseSubscriber = new OperatorWindowBoundaryCloseSubscriber(this, create); if (this.resources.add(operatorWindowBoundaryCloseSubscriber)) { this.windows.getAndIncrement(); publisher.subscribe(operatorWindowBoundaryCloseSubscriber); } } catch (Throwable th2) { this.cancelled = true; subscriber.onError(th2); } } else { this.cancelled = true; subscriber.onError(new MissingBackpressureException("Could not deliver new window due to lack of requests")); } } } else { for (UnicastProcessor<T> onNext : list) { onNext.onNext(NotificationLite.getValue(poll)); } } } } /* access modifiers changed from: package-private */ public void open(B b) { this.queue.offer(new WindowOperation((UnicastProcessor) null, b)); if (enter()) { drainLoop(); } } /* access modifiers changed from: package-private */ public void close(OperatorWindowBoundaryCloseSubscriber<T, V> operatorWindowBoundaryCloseSubscriber) { this.resources.delete(operatorWindowBoundaryCloseSubscriber); this.queue.offer(new WindowOperation(operatorWindowBoundaryCloseSubscriber.w, null)); if (enter()) { drainLoop(); } } } static final class WindowOperation<T, B> { final B open; final UnicastProcessor<T> w; WindowOperation(UnicastProcessor<T> unicastProcessor, B b) { this.w = unicastProcessor; this.open = b; } } static final class OperatorWindowBoundaryOpenSubscriber<T, B> extends DisposableSubscriber<B> { final WindowBoundaryMainSubscriber<T, B, ?> parent; OperatorWindowBoundaryOpenSubscriber(WindowBoundaryMainSubscriber<T, B, ?> windowBoundaryMainSubscriber) { this.parent = windowBoundaryMainSubscriber; } public void onNext(B b) { this.parent.open(b); } public void onError(Throwable th) { this.parent.error(th); } public void onComplete() { this.parent.onComplete(); } } static final class OperatorWindowBoundaryCloseSubscriber<T, V> extends DisposableSubscriber<V> { boolean done; final WindowBoundaryMainSubscriber<T, ?, V> parent; final UnicastProcessor<T> w; OperatorWindowBoundaryCloseSubscriber(WindowBoundaryMainSubscriber<T, ?, V> windowBoundaryMainSubscriber, UnicastProcessor<T> unicastProcessor) { this.parent = windowBoundaryMainSubscriber; this.w = unicastProcessor; } public void onNext(V v) { cancel(); onComplete(); } public void onError(Throwable th) { if (this.done) { RxJavaPlugins.onError(th); return; } this.done = true; this.parent.error(th); } public void onComplete() { if (!this.done) { this.done = true; this.parent.close(this); } } } }
/* * Copyright (C) 2015 Alefe Souza <contato@alefesouza.com> * * 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 aloogle.rebuapp.fragment; import android.annotation.SuppressLint; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.LightingColorFilter; import android.os.Build; import android.os.Bundle; import android.os.AsyncTask; import android.os.Handler; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarActivity; import android.widget.AbsListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.github.ksoichiro.android.observablescrollview.ObservableListView; import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks; import com.melnykov.fab.FloatingActionButton; import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter; import aloogle.rebuapp.R; import aloogle.rebuapp.activity.FragmentActivity; import aloogle.rebuapp.activity.MainActivity; import aloogle.rebuapp.adapter.CardAdapter; import aloogle.rebuapp.lib.JSONParser; import aloogle.rebuapp.other.CustomTextView; import aloogle.rebuapp.other.Other; @SuppressLint("InflateParams") public class ComunicadosFragment extends Fragment implements AbsListView.OnScrollListener, SwipeRefreshLayout.OnRefreshListener { Activity activity; View view, wnet; ObservableListView list; ArrayList <String> idarray = new ArrayList <String> (); ArrayList <String> tipoarray = new ArrayList <String> (); ArrayList <String> dataarray = new ArrayList <String> (); ArrayList <String> tituloarray = new ArrayList <String> (); ArrayList <String> descricaoarray = new ArrayList <String> (); String title; ViewGroup headertime, space; boolean fromnonet, topanel, alreadyLoaded; ProgressBar progressBar; ProgressBarCircularIndeterminate progressBarCompat; SharedPreferences preferences; RelativeLayout relative; private SwipeRefreshLayout mSwipeLayout; private static String url; private static final String TAG_INFO = "info"; private static final String TAG_ID = "id"; private static final String TAG_TIPO = "tipo"; private static final String TAG_DATA = "data"; private static final String TAG_TITULO = "titulo"; private static final String TAG_DESCRICAO = "descricao"; JSONArray info = null; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = getActivity(); } @Override public void onCreate(Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); view = inflater.inflate(R.layout.fragment_main, container, false); preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); url = "http://apps.aloogle.net/schoolapp/rebua/json/main.php?comunicados=true"; list = (ObservableListView)view.findViewById(R.id.list); fromnonet = false; topanel = false; relative = (RelativeLayout)view.findViewById(R.id.fragment); if (!getActivity().getIntent().hasExtra("widgetpos")) { if (Build.VERSION.SDK_INT > 10) { list.setScrollViewCallbacks((ObservableScrollViewCallbacks)getActivity()); list.setTouchInterceptionViewGroup((ViewGroup)getActivity().findViewById(R.id.container)); } if (!MainActivity.home) { MainActivity.titulo = "Comunicados"; ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(MainActivity.titulo); MainActivity.mDrawerList.setItemChecked(4, true); MainActivity.pos = 4; } FloatingActionButton fabpanel = (FloatingActionButton)getActivity().findViewById(R.id.fabpanel); fabpanel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Other.openPanel(getActivity()); topanel = true; } }); } else { FragmentActivity.ActionBarColor(((ActionBarActivity)getActivity()), "Comunicados"); } LayoutInflater inflatere = getActivity().getLayoutInflater(); space = (ViewGroup)inflatere.inflate(R.layout.space, list, false); list.addFooterView(space, null, false); mSwipeLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipe_container); mSwipeLayout.setOnRefreshListener(this); mSwipeLayout.setColorSchemeResources(R.color.primary_color, R.color.primary_color_dark, R.color.primary_color, R.color.primary_color_dark); if (Build.VERSION.SDK_INT >= 21) { progressBar = (ProgressBar)view.findViewById(R.id.progressBar1); if (Other.getColor2(getActivity(), 1).equals("005400")) { progressBar.getIndeterminateDrawable().setColorFilter(new LightingColorFilter(0xFF005400, 0xFF005400)); } else { progressBar.getIndeterminateDrawable().setColorFilter(new LightingColorFilter(0xFF003061, 0xFF003061)); } progressBar.setVisibility(View.VISIBLE); } else { progressBarCompat = (ProgressBarCircularIndeterminate)view.findViewById(R.id.progressBar1); progressBarCompat.setBackgroundColor(Color.parseColor("#ff" + Other.getColor2(getActivity(), 1))); progressBarCompat.setVisibility(View.VISIBLE); } if (Other.isConnected(getActivity())) { offlineJSON(true); new JSONParse().execute(); } else { offlineJSON(false); } return view; } private class JSONParse extends AsyncTask < String, String, JSONObject > { @Override protected void onPreExecute() { if (!getActivity().getIntent().hasExtra("widgetpos")) { new Handler().postDelayed(new Runnable() { @Override public void run() { MainActivity.setRefreshActionButtonState(true, getActivity()); } }, 100); } super.onPreExecute(); } @Override protected JSONObject doInBackground(String...args) { JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(url.replace(" ", "%20")); return json; } @Override protected void onPostExecute(JSONObject json) { if (Build.VERSION.SDK_INT >= 21) { progressBar.setVisibility(View.GONE); } else { progressBarCompat.setVisibility(View.GONE); } mSwipeLayout.setRefreshing(false); if (!getActivity().getIntent().hasExtra("widgetpos")) { MainActivity.setRefreshActionButtonState(false, getActivity()); } if (headertime != null) { list.removeHeaderView(headertime); } SharedPreferences.Editor editor = preferences.edit(); Date currentDate = new Date(); editor.putLong("lastcomunicados", currentDate.getTime()); editor.commit(); try { if (preferences.contains("comunicados")) { if (preferences.getString("comunicados", "").equals(json.toString())) { if (headertime != null) { ClearAll(); offlineJSON(true); } } else { ClearAll(); editor.putString("comunicados", json.toString()); editor.commit(); alreadyLoaded = false; JSONConstructor(json); } } else { editor.putString("comunicados", json.toString()); editor.commit(); JSONConstructor(json); } } catch (Exception e) {} } } public void JSONConstructor(JSONObject json) { try { if (fromnonet) { relative.removeView(wnet); fromnonet = false; } list.setVisibility(View.VISIBLE); if (!alreadyLoaded) { info = json.getJSONArray(TAG_INFO); for (int i = 0; i < info.length(); i++) { JSONObject c = info.getJSONObject(i); String id = c.getString(TAG_ID); String tipo = c.getString(TAG_TIPO); String data = c.getString(TAG_DATA); String titulo = c.getString(TAG_TITULO); String descricao = c.getString(TAG_DESCRICAO); idarray.add(id); tipoarray.add(tipo); dataarray.add(data); tituloarray.add(titulo); descricaoarray.add(descricao); } alreadyLoaded = true; } SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(new CardAdapter(getActivity(), idarray, tipoarray, dataarray, tituloarray, descricaoarray, false)); swingBottomInAnimationAdapter.setAbsListView(list); assert swingBottomInAnimationAdapter.getViewAnimator() != null; swingBottomInAnimationAdapter.getViewAnimator().setInitialDelayMillis(300); list.setAdapter(swingBottomInAnimationAdapter); list.setOnScrollListener(ComunicadosFragment.this); list.setVisibility(View.VISIBLE); } catch (JSONException e) { e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: if (Other.isConnected(getActivity())) { alreadyLoaded = false; new JSONParse().execute(); } else { mSwipeLayout.setRefreshing(false); Toast toast = Toast.makeText(getActivity(), getString(R.string.needinternet), Toast.LENGTH_LONG); toast.show(); } return true; default: return super.onOptionsItemSelected(item); } } public void offlineJSON(boolean haveNet) { if (preferences.contains("comunicados")) { try { String comunicados = preferences.getString("comunicados", "none"); JSONObject json = new JSONObject(comunicados); JSONConstructor(json); if (!haveNet) { if (headertime == null) { headertime = (ViewGroup)getActivity().getLayoutInflater().inflate(R.layout.header2, list, false); CustomTextView time = (CustomTextView)headertime.findViewById(R.id.text); time.setText("Última atualização há " + Other.compareDate(preferences.getLong("lastcomunicados", 0))); list.addHeaderView(headertime, null, false); } else { CustomTextView time = (CustomTextView)headertime.findViewById(R.id.text); time.setText("Última atualização há " + Other.compareDate(preferences.getLong("lastcomunicados", 0))); } } if (Build.VERSION.SDK_INT >= 21) { progressBar.setVisibility(View.GONE); } else { progressBarCompat.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } else { if (!haveNet) { if (Build.VERSION.SDK_INT >= 21) { progressBar.setVisibility(View.GONE); } else { progressBarCompat.setVisibility(View.GONE); } if (!fromnonet) { wnet = getActivity().getLayoutInflater().inflate(R.layout.littlecard, null); CustomTextView warning = (CustomTextView)wnet.findViewById(R.id.text); warning.setText("Você precisa estar conectado à internet pelo menos uma vez para salvar os comunicados."); list.setVisibility(View.GONE); relative.addView(wnet); fromnonet = true; } } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) {} @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (list.getChildCount() > 0 && list.getChildAt(0).getTop() == 0 && list.getFirstVisiblePosition() == 0) { mSwipeLayout.setEnabled(true); } else { mSwipeLayout.setEnabled(false); } } public void onRefresh() { if (Other.isConnected(getActivity())) { alreadyLoaded = false; new JSONParse().execute(); } else { mSwipeLayout.setRefreshing(false); Toast toast = Toast.makeText(getActivity(), getString(R.string.needinternet), Toast.LENGTH_LONG); toast.show(); } } public void ClearAll() { idarray.clear(); tipoarray.clear(); dataarray.clear(); tituloarray.clear(); descricaoarray.clear(); } public void onResume() { if (topanel) { if (Other.isConnected(getActivity())) { alreadyLoaded = false; new JSONParse().execute(); topanel = false; } } super.onResume(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysml.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.sysml.conf.CompilerConfig.ConfigType; import org.apache.sysml.conf.ConfigurationManager; import org.apache.sysml.hops.DataGenOp; import org.apache.sysml.parser.LanguageException.LanguageErrorCodes; import org.apache.sysml.parser.common.CustomErrorListener; import org.apache.sysml.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer; import org.apache.sysml.runtime.util.LocalFileUtils; import org.apache.sysml.runtime.util.MapReduceTool; import org.apache.sysml.runtime.util.UtilFunctions; import org.apache.sysml.utils.JSONHelper; import org.apache.wink.json4j.JSONArray; import org.apache.wink.json4j.JSONObject; public class DataExpression extends DataIdentifier { public static final String RAND_ROWS = "rows"; public static final String RAND_COLS = "cols"; public static final String RAND_MIN = "min"; public static final String RAND_MAX = "max"; public static final String RAND_SPARSITY = "sparsity"; public static final String RAND_SEED = "seed"; public static final String RAND_PDF = "pdf"; public static final String RAND_LAMBDA = "lambda"; public static final String RAND_PDF_UNIFORM = "uniform"; public static final String RAND_BY_ROW = "byrow"; public static final String RAND_DIMNAMES = "dimnames"; public static final String RAND_DATA = "data"; public static final String IO_FILENAME = "iofilename"; public static final String READROWPARAM = "rows"; public static final String READCOLPARAM = "cols"; public static final String READNUMNONZEROPARAM = "nnz"; public static final String FORMAT_TYPE = "format"; public static final String FORMAT_TYPE_VALUE_TEXT = "text"; public static final String FORMAT_TYPE_VALUE_BINARY = "binary"; public static final String FORMAT_TYPE_VALUE_CSV = "csv"; public static final String FORMAT_TYPE_VALUE_MATRIXMARKET = "mm"; public static final String ROWBLOCKCOUNTPARAM = "rows_in_block"; public static final String COLUMNBLOCKCOUNTPARAM = "cols_in_block"; public static final String DATATYPEPARAM = "data_type"; public static final String VALUETYPEPARAM = "value_type"; public static final String DESCRIPTIONPARAM = "description"; public static final String AUTHORPARAM = "author"; public static final String SCHEMAPARAM = "schema"; // Parameter names relevant to reading/writing delimited/csv files public static final String DELIM_DELIMITER = "sep"; public static final String DELIM_HAS_HEADER_ROW = "header"; public static final String DELIM_FILL = "fill"; public static final String DELIM_FILL_VALUE = "default"; //public static final String DELIM_RECODE = "recode"; public static final String DELIM_NA_STRINGS = "na.strings"; public static final String DELIM_NA_STRING_SEP = "\u00b7"; public static final String DELIM_SPARSE = "sparse"; // applicable only for write public static final String[] RAND_VALID_PARAM_NAMES = { RAND_ROWS, RAND_COLS, RAND_MIN, RAND_MAX, RAND_SPARSITY, RAND_SEED, RAND_PDF, RAND_LAMBDA}; public static final String[] MATRIX_VALID_PARAM_NAMES = { RAND_BY_ROW, RAND_DIMNAMES, RAND_DATA, RAND_ROWS, RAND_COLS}; // Valid parameter names in a metadata file public static final String[] READ_VALID_MTD_PARAM_NAMES = { IO_FILENAME, READROWPARAM, READCOLPARAM, READNUMNONZEROPARAM, FORMAT_TYPE, ROWBLOCKCOUNTPARAM, COLUMNBLOCKCOUNTPARAM, DATATYPEPARAM, VALUETYPEPARAM, SCHEMAPARAM, DESCRIPTIONPARAM, // Parameters related to delimited/csv files. DELIM_FILL_VALUE, DELIM_DELIMITER, DELIM_FILL, DELIM_HAS_HEADER_ROW, DELIM_NA_STRINGS }; public static final String[] READ_VALID_PARAM_NAMES = { IO_FILENAME, READROWPARAM, READCOLPARAM, FORMAT_TYPE, DATATYPEPARAM, VALUETYPEPARAM, SCHEMAPARAM, ROWBLOCKCOUNTPARAM, COLUMNBLOCKCOUNTPARAM, READNUMNONZEROPARAM, // Parameters related to delimited/csv files. DELIM_FILL_VALUE, DELIM_DELIMITER, DELIM_FILL, DELIM_HAS_HEADER_ROW, DELIM_NA_STRINGS }; /* Default Values for delimited (CSV) files */ public static final String DEFAULT_DELIM_DELIMITER = ","; public static final boolean DEFAULT_DELIM_HAS_HEADER_ROW = false; public static final boolean DEFAULT_DELIM_FILL = true; public static final double DEFAULT_DELIM_FILL_VALUE = 0.0; public static final boolean DEFAULT_DELIM_SPARSE = false; private DataOp _opcode; private HashMap<String, Expression> _varParams; private boolean _strInit = false; //string initialize private boolean _checkMetadata = true; // local skip meta data reads public DataExpression(){ //do nothing } public void setCheckMetadata(boolean checkMetadata) { _checkMetadata = checkMetadata; } public static DataExpression getDataExpression(String functionName, ArrayList<ParameterExpression> passedParamExprs, String filename, int blp, int bcp, int elp, int ecp, CustomErrorListener errorListener) throws LanguageException { if (functionName == null || passedParamExprs == null) return null; // check if the function name is built-in function // (assign built-in function op if function is built-in) Expression.DataOp dop = null; DataExpression dataExpr = null; if (functionName.equals("read") || functionName.equals("readMM") || functionName.equals("read.csv")) { dop = Expression.DataOp.READ; dataExpr = new DataExpression(dop, new HashMap<String,Expression>(), filename, blp, bcp, elp, ecp); if (functionName.equals("readMM")) dataExpr.addVarParam(DataExpression.FORMAT_TYPE, new StringIdentifier(DataExpression.FORMAT_TYPE_VALUE_MATRIXMARKET, filename, blp, bcp, elp, ecp)); if (functionName.equals("read.csv")) dataExpr.addVarParam(DataExpression.FORMAT_TYPE, new StringIdentifier(DataExpression.FORMAT_TYPE_VALUE_CSV, filename, blp, bcp, elp, ecp)); // validate the filename is the first parameter if (passedParamExprs.size() < 1){ errorListener.validationError(blp, bcp, "read method must have at least filename parameter"); return null; } ParameterExpression pexpr = (passedParamExprs.size() == 0) ? null : passedParamExprs.get(0); if ( (pexpr != null) && (!(pexpr.getName() == null) || (pexpr.getName() != null && pexpr.getName().equalsIgnoreCase(DataExpression.IO_FILENAME)))){ errorListener.validationError(blp, bcp, "first parameter to read statement must be filename"); return null; } else if( pexpr != null ){ dataExpr.addVarParam(DataExpression.IO_FILENAME, pexpr.getExpr()); } // validate all parameters are added only once and valid name for (int i = 1; i < passedParamExprs.size(); i++){ String currName = passedParamExprs.get(i).getName(); Expression currExpr = passedParamExprs.get(i).getExpr(); if (dataExpr.getVarParam(currName) != null){ errorListener.validationError(blp, bcp, "attempted to add IOStatement parameter " + currName + " more than once"); return null; } // verify parameter names for read function boolean isValidName = false; for (String paramName : READ_VALID_PARAM_NAMES){ if (paramName.equals(currName)) isValidName = true; } if (!isValidName){ errorListener.validationError(blp, bcp, "attempted to add invalid read statement parameter " + currName); return null; } dataExpr.addVarParam(currName, currExpr); } } else if (functionName.equalsIgnoreCase("rand")){ dop = Expression.DataOp.RAND; dataExpr = new DataExpression(dop, new HashMap<String,Expression>(), filename, blp, bcp, elp, ecp); for (ParameterExpression currExpr : passedParamExprs){ String pname = currExpr.getName(); Expression pexpr = currExpr.getExpr(); if (pname == null){ errorListener.validationError(blp, bcp, "for rand statement, all arguments must be named parameters"); return null; } dataExpr.addRandExprParam(pname, pexpr); } dataExpr.setRandDefault(); } else if (functionName.equals("matrix")){ dop = Expression.DataOp.MATRIX; dataExpr = new DataExpression(dop, new HashMap<String,Expression>(), filename, blp, bcp, elp, ecp); int namedParamCount = 0, unnamedParamCount = 0; for (ParameterExpression currExpr : passedParamExprs) { if (currExpr.getName() == null) unnamedParamCount++; else namedParamCount++; } // check whether named or unnamed parameters are used if (passedParamExprs.size() < 3){ errorListener.validationError(blp, bcp, "for matrix statement, must specify at least 3 arguments: data, rows, cols"); return null; } if (unnamedParamCount > 1){ if (namedParamCount > 0) { errorListener.validationError(blp, bcp, "for matrix statement, cannot mix named and unnamed parameters"); return null; } if (unnamedParamCount < 3) { errorListener.validationError(blp, bcp, "for matrix statement, must specify at least 3 arguments: data, rows, cols"); return null; } // assume: data, rows, cols, [byRow], [dimNames] dataExpr.addMatrixExprParam(DataExpression.RAND_DATA,passedParamExprs.get(0).getExpr()); dataExpr.addMatrixExprParam(DataExpression.RAND_ROWS,passedParamExprs.get(1).getExpr()); dataExpr.addMatrixExprParam(DataExpression.RAND_COLS,passedParamExprs.get(2).getExpr()); if (unnamedParamCount >= 4) dataExpr.addMatrixExprParam(DataExpression.RAND_BY_ROW,passedParamExprs.get(3).getExpr()); if (unnamedParamCount == 5) dataExpr.addMatrixExprParam(DataExpression.RAND_DIMNAMES,passedParamExprs.get(4).getExpr()); if (unnamedParamCount > 5) { errorListener.validationError(blp, bcp, "for matrix statement, at most 5 arguments supported: data, rows, cols, byrow, dimname"); return null; } } else { // handle first parameter, which is data and may be unnamed ParameterExpression firstParam = passedParamExprs.get(0); if (firstParam.getName() != null && !firstParam.getName().equals(DataExpression.RAND_DATA)){ errorListener.validationError(blp, bcp, "matrix method must have data parameter as first parameter or unnamed parameter"); return null; } else { dataExpr.addMatrixExprParam(DataExpression.RAND_DATA, passedParamExprs.get(0).getExpr()); } for (int i=1; i<passedParamExprs.size(); i++){ if (passedParamExprs.get(i).getName() == null){ errorListener.validationError(blp, bcp, "for matrix statement, cannot mix named and unnamed parameters, only data parameter can be unnammed"); return null; } else { dataExpr.addMatrixExprParam(passedParamExprs.get(i).getName(), passedParamExprs.get(i).getExpr()); } } } dataExpr.setMatrixDefault(); } if (dataExpr != null) { dataExpr.setAllPositions(filename, blp, bcp, elp, ecp); } return dataExpr; } // end method getBuiltinFunctionExpression public void addRandExprParam(String paramName, Expression paramValue) throws LanguageException { // check name is valid boolean found = false; if (paramName != null ){ for (String name : RAND_VALID_PARAM_NAMES){ if (name.equals(paramName)) { found = true; break; } } } if (!found){ raiseValidateError("unexpected parameter \"" + paramName + "\". Legal parameters for Rand statement are " + "(capitalization-sensitive): " + RAND_ROWS + ", " + RAND_COLS + ", " + RAND_MIN + ", " + RAND_MAX + ", " + RAND_SPARSITY + ", " + RAND_SEED + ", " + RAND_PDF + ", " + RAND_LAMBDA); } if (getVarParam(paramName) != null){ raiseValidateError("attempted to add Rand statement parameter " + paramValue + " more than once"); } // Process the case where user provides double values to rows or cols if (paramName.equals(RAND_ROWS) && paramValue instanceof DoubleIdentifier){ paramValue = new IntIdentifier((long)((DoubleIdentifier)paramValue).getValue(), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); } else if (paramName.equals(RAND_COLS) && paramValue instanceof DoubleIdentifier){ paramValue = new IntIdentifier((long)((DoubleIdentifier)paramValue).getValue(), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); } // add the parameter to expression list paramValue.setAllPositions(this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(paramName,paramValue); } public void addMatrixExprParam(String paramName, Expression paramValue) throws LanguageException { // check name is valid boolean found = false; if (paramName != null ){ for (String name : MATRIX_VALID_PARAM_NAMES){ if (name.equals(paramName)) { found = true; } } } if (!found){ raiseValidateError("unexpected parameter \"" + paramName + "\". Legal parameters for matrix statement are " + "(capitalization-sensitive): " + RAND_DATA + ", " + RAND_ROWS + ", " + RAND_COLS + ", " + RAND_BY_ROW); } if (getVarParam(paramName) != null) { raiseValidateError("attempted to add matrix statement parameter " + paramValue + " more than once"); } // Process the case where user provides double values to rows or cols if (paramName.equals(RAND_ROWS) && paramValue instanceof DoubleIdentifier){ paramValue = new IntIdentifier((long)((DoubleIdentifier)paramValue).getValue(), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); } else if (paramName.equals(RAND_COLS) && paramValue instanceof DoubleIdentifier){ paramValue = new IntIdentifier((long)((DoubleIdentifier)paramValue).getValue(), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); } // add the parameter to expression list paramValue.setAllPositions(this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(paramName,paramValue); } public DataExpression(DataOp op, HashMap<String,Expression> varParams, String filename, int blp, int bcp, int elp, int ecp) { _kind = Kind.DataOp; _opcode = op; _varParams = varParams; this.setAllPositions(filename, blp, bcp, elp, ecp); } public Expression rewriteExpression(String prefix) throws LanguageException { HashMap<String,Expression> newVarParams = new HashMap<String,Expression>(); for( Entry<String, Expression> e : _varParams.entrySet() ){ String key = e.getKey(); Expression newExpr = e.getValue().rewriteExpression(prefix); newVarParams.put(key, newExpr); } DataExpression retVal = new DataExpression(_opcode, newVarParams, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); retVal._strInit = this._strInit; return retVal; } /** * By default we use rowwise matrix reshape according to our internal dense/sparse matrix representations. * ByRow specifies both input and output orientation. Note that this is different from R, where inputs are * always read by-column and the default for byRow is by-column as well. */ public void setMatrixDefault(){ if (getVarParam(RAND_BY_ROW) == null) addVarParam(RAND_BY_ROW, new BooleanIdentifier(true, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } public void setRandDefault(){ if (getVarParam(RAND_ROWS)== null){ IntIdentifier id = new IntIdentifier(1L, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_ROWS, id); } if (getVarParam(RAND_COLS)== null){ IntIdentifier id = new IntIdentifier(1L, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_COLS, id); } if (getVarParam(RAND_MIN)== null){ DoubleIdentifier id = new DoubleIdentifier(0.0, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_MIN, id); } if (getVarParam(RAND_MAX)== null){ DoubleIdentifier id = new DoubleIdentifier(1.0, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_MAX, id); } if (getVarParam(RAND_SPARSITY)== null){ DoubleIdentifier id = new DoubleIdentifier(1.0, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_SPARSITY, id); } if (getVarParam(RAND_SEED)== null){ IntIdentifier id = new IntIdentifier(DataGenOp.UNSPECIFIED_SEED, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_SEED, id); } if (getVarParam(RAND_PDF)== null){ StringIdentifier id = new StringIdentifier(RAND_PDF_UNIFORM, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_PDF, id); } if (getVarParam(RAND_LAMBDA)== null){ DoubleIdentifier id = new DoubleIdentifier(1.0, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn()); addVarParam(RAND_LAMBDA, id); } } public void setOpCode(DataOp op) { _opcode = op; } public DataOp getOpCode() { return _opcode; } public HashMap<String,Expression> getVarParams() { return _varParams; } public void setVarParams(HashMap<String, Expression> varParams) { _varParams = varParams; } public Expression getVarParam(String name) { return _varParams.get(name); } public void addVarParam(String name, Expression value){ _varParams.put(name, value); // if required, initialize values setFilename(value.getFilename()); if (getBeginLine() == 0) setBeginLine(value.getBeginLine()); if (getBeginColumn() == 0) setBeginColumn(value.getBeginColumn()); if (getEndLine() == 0) setEndLine(value.getEndLine()); if (getEndColumn() == 0) setEndColumn(value.getEndColumn()); } public void removeVarParam(String name) { _varParams.remove(name); } private String getInputFileName(HashMap<String, ConstIdentifier> currConstVars, boolean conditional) throws LanguageException { String filename = null; Expression fileNameExpr = getVarParam(IO_FILENAME); if (fileNameExpr instanceof ConstIdentifier){ return fileNameExpr.toString(); } else if (fileNameExpr instanceof BinaryExpression){ BinaryExpression expr = (BinaryExpression)fileNameExpr; if (expr.getKind()== Expression.Kind.BinaryOp){ Expression.BinaryOp op = expr.getOpCode(); switch (op){ case PLUS: filename = ""; filename = fileNameCat(expr, currConstVars, filename, conditional); // Since we have computed the value of filename, we update // varParams with a const string value StringIdentifier fileString = new StringIdentifier(filename, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); removeVarParam(IO_FILENAME); addVarParam(IO_FILENAME, fileString); break; default: raiseValidateError("for read method, parameter " + IO_FILENAME + " can only be const string concatenations. ", conditional); } } } else { raiseValidateError("for read method, parameter " + IO_FILENAME + " can only be a const string or const string concatenations. ", conditional); } return filename; } public static String getMTDFileName(String inputFileName) throws LanguageException { String mtdName = inputFileName + ".mtd"; //validate read filename if( !LocalFileUtils.validateExternalFilename(mtdName, true) ) throw new LanguageException("Invalid (non-trustworthy) hdfs read filename."); return mtdName; } /** * Validate parse tree : Process Data Expression in an assignment * statement */ @Override public void validateExpression(HashMap<String, DataIdentifier> ids, HashMap<String, ConstIdentifier> currConstVars, boolean conditional) throws LanguageException { // validate all input parameters for ( Entry<String,Expression> e : getVarParams().entrySet() ) { String s = e.getKey(); Expression inputParamExpr = e.getValue(); if (inputParamExpr instanceof FunctionCallIdentifier) { raiseValidateError("UDF function call not supported as parameter to built-in function call", false,LanguageErrorCodes.INVALID_PARAMETERS); } inputParamExpr.validateExpression(ids, currConstVars, conditional); if ( getVarParam(s).getOutput().getDataType() != DataType.SCALAR && !s.equals(RAND_DATA)) { raiseValidateError("Non-scalar data types are not supported for data expression.", conditional,LanguageErrorCodes.INVALID_PARAMETERS); } } //general data expression constant propagation performConstantPropagationRand( currConstVars ); performConstantPropagationReadWrite( currConstVars ); // check if data parameter of matrix is scalar or matrix -- if scalar, use Rand instead Expression dataParam1 = getVarParam(RAND_DATA); if (dataParam1 == null && getOpCode().equals(DataOp.MATRIX)){ raiseValidateError("for matrix, must defined data parameter", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } if (dataParam1 != null && dataParam1.getOutput().getDataType() == DataType.SCALAR /*&& dataParam instanceof ConstIdentifier*/ ){ //MB: note we should not check for const identifiers here, because otherwise all matrix constructors with //variable input are routed to a reshape operation (but it works only on matrices and hence, crashes) // replace DataOp MATRIX with RAND -- Rand handles matrix generation for Scalar values // replace data parameter with min / max within Rand case below this.setOpCode(DataOp.RAND); } // IMPORTANT: for each operation, one must handle unnamed parameters switch (this.getOpCode()) { case READ: if (getVarParam(DATATYPEPARAM) != null && !(getVarParam(DATATYPEPARAM) instanceof StringIdentifier)){ raiseValidateError("for read statement, parameter " + DATATYPEPARAM + " can only be a string. " + "Valid values are: " + Statement.MATRIX_DATA_TYPE +", " + Statement.SCALAR_DATA_TYPE, conditional); } String dataTypeString = (getVarParam(DATATYPEPARAM) == null) ? null : getVarParam(DATATYPEPARAM).toString(); // disallow certain parameters while reading a scalar if (dataTypeString != null && dataTypeString.equalsIgnoreCase(Statement.SCALAR_DATA_TYPE)){ if ( getVarParam(READROWPARAM) != null || getVarParam(READCOLPARAM) != null || getVarParam(ROWBLOCKCOUNTPARAM) != null || getVarParam(COLUMNBLOCKCOUNTPARAM) != null || getVarParam(FORMAT_TYPE) != null || getVarParam(DELIM_DELIMITER) != null || getVarParam(DELIM_HAS_HEADER_ROW) != null || getVarParam(DELIM_FILL) != null || getVarParam(DELIM_FILL_VALUE) != null || getVarParam(DELIM_NA_STRINGS) != null ) { raiseValidateError("Invalid parameters in read statement of a scalar: " + toString() + ". Only " + VALUETYPEPARAM + " is allowed.", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } } JSONObject configObject = null; // Process expressions in input filename String inputFileName = getInputFileName(currConstVars, conditional); // Obtain and validate metadata filename String mtdFileName = getMTDFileName(inputFileName); // track whether should attempt to read MTD file or not boolean shouldReadMTD = _checkMetadata && !ConfigurationManager .getCompilerConfigFlag(ConfigType.IGNORE_READ_WRITE_METADATA); // Check for file existence (before metadata parsing for meaningful error messages) if( shouldReadMTD //skip check for jmlc/mlcontext && !MapReduceTool.existsFileOnHDFS(inputFileName)) { String fsext = InfrastructureAnalyzer.isLocalMode() ? "FS (local mode)" : "HDFS"; raiseValidateError("Read input file does not exist on "+fsext+": " + inputFileName, conditional, LanguageErrorCodes.INVALID_PARAMETERS); } // track whether format type has been inferred boolean inferredFormatType = false; // get format type string String formatTypeString = (getVarParam(FORMAT_TYPE) == null) ? null : getVarParam(FORMAT_TYPE).toString(); // check if file is matrix market format if (formatTypeString == null && shouldReadMTD){ boolean isMatrixMarketFormat = checkHasMatrixMarketFormat(inputFileName, mtdFileName, conditional); if (isMatrixMarketFormat){ formatTypeString = FORMAT_TYPE_VALUE_MATRIXMARKET; addVarParam(FORMAT_TYPE,new StringIdentifier(FORMAT_TYPE_VALUE_MATRIXMARKET, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); inferredFormatType = true; shouldReadMTD = false; } } // check if file is delimited format if (formatTypeString == null && shouldReadMTD ) { boolean isDelimitedFormat = checkHasDelimitedFormat(inputFileName, conditional); if (isDelimitedFormat){ addVarParam(FORMAT_TYPE,new StringIdentifier(FORMAT_TYPE_VALUE_CSV, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); formatTypeString = FORMAT_TYPE_VALUE_CSV; inferredFormatType = true; //shouldReadMTD = false; } } if (formatTypeString != null && formatTypeString.equalsIgnoreCase(FORMAT_TYPE_VALUE_MATRIXMARKET)){ /* * handle MATRIXMARKET_FORMAT_TYPE format * * 1) only allow IO_FILENAME as ONLY valid parameter * * 2) open the file * A) verify header line (1st line) equals * B) read and discard comment lines * C) get size information from sizing info line --- M N L */ for (String key : _varParams.keySet()){ if ( !(key.equals(IO_FILENAME) || key.equals(FORMAT_TYPE) ) ){ raiseValidateError("Invalid parameters in readMM statement: " + toString() + ". Only " + IO_FILENAME + " is allowed.", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } } // should NOT attempt to read MTD file for MatrixMarket format shouldReadMTD = false; // get metadata from MatrixMarket format file String[] headerLines = readMatrixMarketFile(inputFileName, conditional); // process 1st line of MatrixMarket format -- must be identical to legal header String legalHeaderMM = "%%MatrixMarket matrix coordinate real general"; if (headerLines != null && headerLines.length >= 2){ String firstLine = headerLines[0].trim(); if (!firstLine.equals(legalHeaderMM)){ raiseValidateError("Unsupported format in MatrixMarket file: " + headerLines[0] + ". Only supported format in MatrixMarket file has header line " + legalHeaderMM, conditional, LanguageErrorCodes.INVALID_PARAMETERS); } // process 2nd line of MatrixMarket format -- must have size information String secondLine = headerLines[1]; String[] sizeInfo = secondLine.trim().split("\\s+"); if (sizeInfo.length != 3){ raiseValidateError("Unsupported size line in MatrixMarket file: " + headerLines[1] + ". Only supported format in MatrixMarket file has size line: <NUM ROWS> <NUM COLS> <NUM NON-ZEROS>, where each value is an integer.", conditional); } long rowsCount = -1, colsCount = -1, nnzCount = -1; try { rowsCount = Long.parseLong(sizeInfo[0]); if (rowsCount < 1) throw new Exception("invalid rows count"); addVarParam(READROWPARAM, new IntIdentifier(rowsCount, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } catch(Exception e){ raiseValidateError("In MatrixMarket file " + getVarParam(IO_FILENAME) + " invalid row count " + sizeInfo[0] + " (must be long value >= 1). Sizing info line from file: " + headerLines[1], conditional, LanguageErrorCodes.INVALID_PARAMETERS); } try { colsCount = Long.parseLong(sizeInfo[1]); if (colsCount < 1) throw new Exception("invalid cols count"); addVarParam(READCOLPARAM, new IntIdentifier(colsCount, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } catch(Exception e){ raiseValidateError("In MatrixMarket file " + getVarParam(IO_FILENAME) + " invalid column count " + sizeInfo[1] + " (must be long value >= 1). Sizing info line from file: " + headerLines[1], conditional, LanguageErrorCodes.INVALID_PARAMETERS); } try { nnzCount = Long.parseLong(sizeInfo[2]); if (nnzCount < 1) throw new Exception("invalid nnz count"); addVarParam("nnz", new IntIdentifier(nnzCount, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } catch(Exception e){ raiseValidateError("In MatrixMarket file " + getVarParam(IO_FILENAME) + " invalid number non-zeros " + sizeInfo[2] + " (must be long value >= 1). Sizing info line from file: " + headerLines[1], conditional, LanguageErrorCodes.INVALID_PARAMETERS); } } } configObject = null; if (shouldReadMTD){ configObject = readMetadataFile(mtdFileName, conditional); // if the MTD file exists, check the values specified in read statement match values in metadata MTD file if (configObject != null){ parseMetaDataFileParameters(mtdFileName, configObject, conditional); inferredFormatType = true; } else { LOG.warn("Metadata file: " + new Path(mtdFileName) + " not provided"); } } boolean isCSV = false; isCSV = (formatTypeString != null && formatTypeString.equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV)); if (isCSV){ // Handle delimited file format // // 1) only allow IO_FILENAME, _HEADER_ROW, FORMAT_DELIMITER, READROWPARAM, READCOLPARAM // // 2) open the file // // there should be no MTD file for delimited file format shouldReadMTD = true; // only allow IO_FILENAME, HAS_HEADER_ROW, FORMAT_DELIMITER, READROWPARAM, READCOLPARAM // as ONLY valid parameters if( !inferredFormatType ){ for (String key : _varParams.keySet()){ if (! (key.equals(IO_FILENAME) || key.equals(FORMAT_TYPE) || key.equals(DELIM_HAS_HEADER_ROW) || key.equals(DELIM_DELIMITER) || key.equals(DELIM_FILL) || key.equals(DELIM_FILL_VALUE) || key.equals(READROWPARAM) || key.equals(READCOLPARAM) || key.equals(READNUMNONZEROPARAM) || key.equals(DATATYPEPARAM) || key.equals(VALUETYPEPARAM) || key.equals(SCHEMAPARAM)) ) { String msg = "Only parameters allowed are: " + IO_FILENAME + "," + SCHEMAPARAM + "," + DELIM_HAS_HEADER_ROW + "," + DELIM_DELIMITER + "," + DELIM_FILL + "," + DELIM_FILL_VALUE + "," + READROWPARAM + "," + READCOLPARAM; raiseValidateError("Invalid parameter " + key + " in read statement: " + toString() + ". " + msg, conditional, LanguageErrorCodes.INVALID_PARAMETERS); } } } // DEFAULT for "sep" : "," if (getVarParam(DELIM_DELIMITER) == null){ addVarParam(DELIM_DELIMITER, new StringIdentifier(DEFAULT_DELIM_DELIMITER, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } else { if ( (getVarParam(DELIM_DELIMITER) instanceof ConstIdentifier) && (! (getVarParam(DELIM_DELIMITER) instanceof StringIdentifier))) { raiseValidateError("For delimited file '" + getVarParam(DELIM_DELIMITER) + "' must be a string value ", conditional); } } // DEFAULT for "default": 0 if (getVarParam(DELIM_FILL_VALUE) == null){ addVarParam(DELIM_FILL_VALUE, new DoubleIdentifier(DEFAULT_DELIM_FILL_VALUE, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } else { if ( (getVarParam(DELIM_FILL_VALUE) instanceof ConstIdentifier) && (! (getVarParam(DELIM_FILL_VALUE) instanceof IntIdentifier || getVarParam(DELIM_FILL_VALUE) instanceof DoubleIdentifier))) { raiseValidateError("For delimited file '" + getVarParam(DELIM_FILL_VALUE) + "' must be a numeric value ", conditional); } } // DEFAULT for "header": boolean false if (getVarParam(DELIM_HAS_HEADER_ROW) == null){ addVarParam(DELIM_HAS_HEADER_ROW, new BooleanIdentifier(DEFAULT_DELIM_HAS_HEADER_ROW, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } else { if ((getVarParam(DELIM_HAS_HEADER_ROW) instanceof ConstIdentifier) && (! (getVarParam(DELIM_HAS_HEADER_ROW) instanceof BooleanIdentifier))) { raiseValidateError("For delimited file '" + getVarParam(DELIM_HAS_HEADER_ROW) + "' must be a boolean value ", conditional); } } // DEFAULT for "fill": boolean false if (getVarParam(DELIM_FILL) == null){ addVarParam(DELIM_FILL,new BooleanIdentifier(DEFAULT_DELIM_FILL, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } else { if ((getVarParam(DELIM_FILL) instanceof ConstIdentifier) && (! (getVarParam(DELIM_FILL) instanceof BooleanIdentifier))) { raiseValidateError("For delimited file '" + getVarParam(DELIM_FILL) + "' must be a boolean value ", conditional); } } } dataTypeString = (getVarParam(DATATYPEPARAM) == null) ? null : getVarParam(DATATYPEPARAM).toString(); if ( dataTypeString == null || dataTypeString.equalsIgnoreCase(Statement.MATRIX_DATA_TYPE) || dataTypeString.equalsIgnoreCase(Statement.FRAME_DATA_TYPE)) { boolean isMatrix = false; if ( dataTypeString == null || dataTypeString.equalsIgnoreCase(Statement.MATRIX_DATA_TYPE)) isMatrix = true; // set data type getOutput().setDataType(isMatrix ? DataType.MATRIX : DataType.FRAME); // set number non-zeros Expression ennz = this.getVarParam("nnz"); long nnz = -1; if( ennz != null ) { nnz = Long.valueOf(ennz.toString()); getOutput().setNnz(nnz); } // Following dimension checks must be done when data type = MATRIX_DATA_TYPE // initialize size of target data identifier to UNKNOWN getOutput().setDimensions(-1, -1); if ( !isCSV && ConfigurationManager.getCompilerConfig() .getBool(ConfigType.REJECT_READ_WRITE_UNKNOWNS) //skip check for csv format / jmlc api && (getVarParam(READROWPARAM) == null || getVarParam(READCOLPARAM) == null) ) { raiseValidateError("Missing or incomplete dimension information in read statement: " + mtdFileName, conditional, LanguageErrorCodes.INVALID_PARAMETERS); } if (getVarParam(READROWPARAM) instanceof ConstIdentifier && getVarParam(READCOLPARAM) instanceof ConstIdentifier) { // these are strings that are long values Long dim1 = (getVarParam(READROWPARAM) == null) ? null : Long.valueOf( getVarParam(READROWPARAM).toString()); Long dim2 = (getVarParam(READCOLPARAM) == null) ? null : Long.valueOf( getVarParam(READCOLPARAM).toString()); if ( !isCSV && (dim1 <= 0 || dim2 <= 0) && ConfigurationManager .getCompilerConfig().getBool(ConfigType.REJECT_READ_WRITE_UNKNOWNS) ) { raiseValidateError("Invalid dimension information in read statement", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } // set dim1 and dim2 values if (dim1 != null && dim2 != null){ getOutput().setDimensions(dim1, dim2); } else if (!isCSV && ((dim1 != null) || (dim2 != null))) { raiseValidateError("Partial dimension information in read statement", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } } // initialize block dimensions to UNKNOWN getOutput().setBlockDimensions(-1, -1); // find "format": 1=text, 2=binary int format = 1; // default is "text" String fmt = (getVarParam(FORMAT_TYPE) == null ? null : getVarParam(FORMAT_TYPE).toString()); if (fmt == null || fmt.equalsIgnoreCase("text")){ getOutput().setFormatType(FormatType.TEXT); format = 1; } else if ( fmt.equalsIgnoreCase("binary") ) { getOutput().setFormatType(FormatType.BINARY); format = 2; } else if ( fmt.equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV)) { getOutput().setFormatType(FormatType.CSV); format = 1; } else if ( fmt.equalsIgnoreCase(FORMAT_TYPE_VALUE_MATRIXMARKET) ) { getOutput().setFormatType(FormatType.MM); format = 1; } else { raiseValidateError("Invalid format '" + fmt+ "' in statement: " + this.toString(), conditional); } if (getVarParam(ROWBLOCKCOUNTPARAM) instanceof ConstIdentifier && getVarParam(COLUMNBLOCKCOUNTPARAM) instanceof ConstIdentifier) { Long rowBlockCount = (getVarParam(ROWBLOCKCOUNTPARAM) == null) ? null : Long.valueOf(getVarParam(ROWBLOCKCOUNTPARAM).toString()); Long columnBlockCount = (getVarParam(COLUMNBLOCKCOUNTPARAM) == null) ? null : Long.valueOf(getVarParam(COLUMNBLOCKCOUNTPARAM).toString()); if ((rowBlockCount != null) && (columnBlockCount != null)) { getOutput().setBlockDimensions(rowBlockCount, columnBlockCount); } else if ((rowBlockCount != null) || (columnBlockCount != null)) { raiseValidateError("Partial block dimension information in read statement", conditional, LanguageErrorCodes.INVALID_PARAMETERS); } else { getOutput().setBlockDimensions(-1, -1); } } // block dimensions must be -1x-1 when format="text" // NOTE MB: disabled validate of default blocksize for inputs w/ format="binary" // because we automatically introduce reblocks if blocksizes don't match if ( ( (format == 1 || !isMatrix) && (getOutput().getRowsInBlock() != -1 || getOutput().getColumnsInBlock() != -1) ) ){ raiseValidateError("Invalid block dimensions (" + getOutput().getRowsInBlock() + "," + getOutput().getColumnsInBlock() + ") when format=" + getVarParam(FORMAT_TYPE) + " in \"" + this.toString() + "\".", conditional); } } else if ( dataTypeString.equalsIgnoreCase(Statement.SCALAR_DATA_TYPE)) { getOutput().setDataType(DataType.SCALAR); getOutput().setNnz(-1L); } else{ raiseValidateError("Unknown Data Type " + dataTypeString + ". Valid values: " + Statement.SCALAR_DATA_TYPE +", " + Statement.MATRIX_DATA_TYPE, conditional, LanguageErrorCodes.INVALID_PARAMETERS); } // handle value type parameter if (getVarParam(VALUETYPEPARAM) != null && !(getVarParam(VALUETYPEPARAM) instanceof StringIdentifier)){ raiseValidateError("for read method, parameter " + VALUETYPEPARAM + " can only be a string. " + "Valid values are: " + Statement.DOUBLE_VALUE_TYPE +", " + Statement.INT_VALUE_TYPE + ", " + Statement.BOOLEAN_VALUE_TYPE + ", " + Statement.STRING_VALUE_TYPE, conditional); } // Identify the value type (used only for read method) String valueTypeString = getVarParam(VALUETYPEPARAM) == null ? null : getVarParam(VALUETYPEPARAM).toString(); if (valueTypeString != null) { if (valueTypeString.equalsIgnoreCase(Statement.DOUBLE_VALUE_TYPE)) { getOutput().setValueType(ValueType.DOUBLE); } else if (valueTypeString.equalsIgnoreCase(Statement.STRING_VALUE_TYPE)) { getOutput().setValueType(ValueType.STRING); } else if (valueTypeString.equalsIgnoreCase(Statement.INT_VALUE_TYPE)) { getOutput().setValueType(ValueType.INT); } else if (valueTypeString.equalsIgnoreCase(Statement.BOOLEAN_VALUE_TYPE)) { getOutput().setValueType(ValueType.BOOLEAN); } else { raiseValidateError("Unknown Value Type " + valueTypeString + ". Valid values are: " + Statement.DOUBLE_VALUE_TYPE +", " + Statement.INT_VALUE_TYPE + ", " + Statement.BOOLEAN_VALUE_TYPE + ", " + Statement.STRING_VALUE_TYPE, conditional); } } else { getOutput().setValueType(ValueType.DOUBLE); } break; case WRITE: // for delimited format, if no delimiter specified THEN set default "," if (getVarParam(FORMAT_TYPE) == null || getVarParam(FORMAT_TYPE).toString().equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV)){ if (getVarParam(DELIM_DELIMITER) == null){ addVarParam(DELIM_DELIMITER, new StringIdentifier(DEFAULT_DELIM_DELIMITER, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } if (getVarParam(DELIM_HAS_HEADER_ROW) == null){ addVarParam(DELIM_HAS_HEADER_ROW, new BooleanIdentifier(DEFAULT_DELIM_HAS_HEADER_ROW, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } if (getVarParam(DELIM_SPARSE) == null){ addVarParam(DELIM_SPARSE, new BooleanIdentifier(DEFAULT_DELIM_SPARSE, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getBeginLine(), this.getBeginColumn())); } } /* NOTE MB: disabled filename concatenation because we now support dynamic rewrite if (getVarParam(IO_FILENAME) instanceof BinaryExpression){ BinaryExpression expr = (BinaryExpression)getVarParam(IO_FILENAME); if (expr.getKind()== Expression.Kind.BinaryOp){ Expression.BinaryOp op = expr.getOpCode(); switch (op){ case PLUS: mtdFileName = ""; mtdFileName = fileNameCat(expr, currConstVars, mtdFileName); // Since we have computed the value of filename, we update // varParams with a const string value StringIdentifier fileString = new StringIdentifier(mtdFileName, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); removeVarParam(IO_FILENAME); addVarParam(IO_FILENAME, fileString); break; default: raiseValidateError("for OutputStatement, parameter " + IO_FILENAME + " can only be a const string or const string concatenations. ", conditional); } } }*/ //validate read filename String fnameWrite = getVarParam(IO_FILENAME).toString(); if( !LocalFileUtils.validateExternalFilename(fnameWrite, true) ) //always unconditional raiseValidateError("Invalid (non-trustworthy) hdfs write filename.", false); if (getVarParam(FORMAT_TYPE) == null || getVarParam(FORMAT_TYPE).toString().equalsIgnoreCase("text")) getOutput().setBlockDimensions(-1, -1); else if (getVarParam(FORMAT_TYPE).toString().equalsIgnoreCase("binary")) getOutput().setBlockDimensions(ConfigurationManager.getBlocksize(), ConfigurationManager.getBlocksize()); else if (getVarParam(FORMAT_TYPE).toString().equalsIgnoreCase(FORMAT_TYPE_VALUE_MATRIXMARKET) || (getVarParam(FORMAT_TYPE).toString().equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV))) getOutput().setBlockDimensions(-1, -1); else{ raiseValidateError("Invalid format " + getVarParam(FORMAT_TYPE) + " in statement: " + this.toString(), conditional); } break; case RAND: Expression dataParam = getVarParam(RAND_DATA); if( dataParam != null ) { // handle input variable (matrix/scalar) if( dataParam instanceof DataIdentifier ) { addVarParam(RAND_MIN, dataParam); addVarParam(RAND_MAX, dataParam); } // handle integer constant else if (dataParam instanceof IntIdentifier) { long roundedValue = ((IntIdentifier)dataParam).getValue(); Expression minExpr = new DoubleIdentifier(roundedValue, getFilename(), getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn()); addVarParam(RAND_MIN, minExpr); addVarParam(RAND_MAX, minExpr); } // handle double constant else if (dataParam instanceof DoubleIdentifier) { double roundedValue = ((DoubleIdentifier)dataParam).getValue(); Expression minExpr = new DoubleIdentifier(roundedValue, getFilename(), getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn()); addVarParam(RAND_MIN, minExpr); addVarParam(RAND_MAX, minExpr); } // handle string constant (string init) else if (dataParam instanceof StringIdentifier) { String data = ((StringIdentifier)dataParam).getValue(); Expression minExpr = new StringIdentifier(data, getFilename(), getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn()); addVarParam(RAND_MIN, minExpr); addVarParam(RAND_MAX, minExpr); _strInit = true; } else { // handle general expression dataParam.validateExpression(ids, currConstVars, conditional); addVarParam(RAND_MIN, dataParam); addVarParam(RAND_MAX, dataParam); } removeVarParam(RAND_DATA); removeVarParam(RAND_BY_ROW); this.setRandDefault(); } //check valid parameters for( String key : _varParams.keySet() ) { boolean found = false; for (String name : RAND_VALID_PARAM_NAMES){ found |= name.equals(key); } if (!found){ raiseValidateError("unexpected parameter \"" + key + "\". Legal parameters for Rand statement are " + "(capitalization-sensitive): " + RAND_ROWS + ", " + RAND_COLS + ", " + RAND_MIN + ", " + RAND_MAX + ", " + RAND_SPARSITY + ", " + RAND_SEED + ", " + RAND_PDF + ", " + RAND_LAMBDA, conditional); } } //parameters w/ support for variable inputs if (getVarParam(RAND_ROWS) instanceof StringIdentifier || getVarParam(RAND_ROWS) instanceof BooleanIdentifier){ raiseValidateError("for Rand statement " + RAND_ROWS + " has incorrect value type", conditional); } if (getVarParam(RAND_COLS) instanceof StringIdentifier || getVarParam(RAND_COLS) instanceof BooleanIdentifier){ raiseValidateError("for Rand statement " + RAND_COLS + " has incorrect value type", conditional); } if (getVarParam(RAND_SEED) instanceof StringIdentifier || getVarParam(RAND_SEED) instanceof BooleanIdentifier) { raiseValidateError("for Rand statement " + RAND_SEED + " has incorrect value type", conditional); } if ((getVarParam(RAND_MAX) instanceof StringIdentifier && !_strInit) || getVarParam(RAND_MAX) instanceof BooleanIdentifier) { raiseValidateError("for Rand statement " + RAND_MAX + " has incorrect value type", conditional); } if ((getVarParam(RAND_MIN) instanceof StringIdentifier && !_strInit) || getVarParam(RAND_MIN) instanceof BooleanIdentifier) { raiseValidateError("for Rand statement " + RAND_MIN + " has incorrect value type", conditional); } //parameters w/o support for variable inputs (requires double/int or string constants) if (!(getVarParam(RAND_SPARSITY) instanceof DoubleIdentifier || getVarParam(RAND_SPARSITY) instanceof IntIdentifier)) { raiseValidateError("for Rand statement " + RAND_SPARSITY + " has incorrect value type", conditional); } if (!(getVarParam(RAND_PDF) instanceof StringIdentifier)) { raiseValidateError("for Rand statement " + RAND_PDF + " has incorrect value type", conditional); } Expression lambda = getVarParam(RAND_LAMBDA); if (!( (lambda instanceof DataIdentifier || lambda instanceof ConstIdentifier) && (lambda.getOutput().getValueType() == ValueType.DOUBLE || lambda.getOutput().getValueType() == ValueType.INT) )) { raiseValidateError("for Rand statement " + RAND_LAMBDA + " has incorrect data type", conditional); } long rowsLong = -1L, colsLong = -1L; /////////////////////////////////////////////////////////////////// // HANDLE ROWS /////////////////////////////////////////////////////////////////// Expression rowsExpr = getVarParam(RAND_ROWS); if (rowsExpr instanceof IntIdentifier) { if (((IntIdentifier)rowsExpr).getValue() >= 1 ) { rowsLong = ((IntIdentifier)rowsExpr).getValue(); } else { raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + ((IntIdentifier)rowsExpr).getValue(), conditional); } } else if (rowsExpr instanceof DoubleIdentifier) { if (((DoubleIdentifier)rowsExpr).getValue() >= 1 ) { rowsLong = UtilFunctions.toLong(Math.floor(((DoubleIdentifier)rowsExpr).getValue())); } else { raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + rowsExpr.toString(), conditional); } } else if (rowsExpr instanceof DataIdentifier && !(rowsExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)rowsExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // check rows is >= 1 --- throw exception if (((IntIdentifier)constValue).getValue() < 1){ raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update row expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); rowsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_ROWS, rowsExpr); rowsLong = roundedValue; } // handle double constant else if (constValue instanceof DoubleIdentifier){ if (((DoubleIdentifier)constValue).getValue() < 1.0){ raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update row expr with new IntIdentifier (rounded down) long roundedValue = Double.valueOf(Math.floor(((DoubleIdentifier)constValue).getValue())).longValue(); rowsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_ROWS, rowsExpr); rowsLong = roundedValue; } else { // exception -- rows must be integer or double constant raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } } else { // handle general expression rowsExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression rowsExpr.validateExpression(ids, currConstVars, conditional); } /////////////////////////////////////////////////////////////////// // HANDLE COLUMNS /////////////////////////////////////////////////////////////////// Expression colsExpr = getVarParam(RAND_COLS); if (colsExpr instanceof IntIdentifier) { if (((IntIdentifier)colsExpr).getValue() >= 1 ) { colsLong = ((IntIdentifier)colsExpr).getValue(); } else { raiseValidateError("In rand statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString(), conditional); } } else if (colsExpr instanceof DoubleIdentifier) { if (((DoubleIdentifier)colsExpr).getValue() >= 1 ) { colsLong = Double.valueOf((Math.floor(((DoubleIdentifier)colsExpr).getValue()))).longValue(); } else { raiseValidateError("In rand statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString(), conditional); } } else if (colsExpr instanceof DataIdentifier && !(colsExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)colsExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // check cols is >= 1 --- throw exception if (((IntIdentifier)constValue).getValue() < 1){ raiseValidateError("In rand statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update col expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); colsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_COLS, colsExpr); colsLong = roundedValue; } // handle double constant else if (constValue instanceof DoubleIdentifier){ if (((DoubleIdentifier)constValue).getValue() < 1){ raiseValidateError("In rand statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update col expr with new IntIdentifier (rounded down) long roundedValue = Double.valueOf(Math.floor(((DoubleIdentifier)constValue).getValue())).longValue(); colsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_COLS, colsExpr); colsLong = roundedValue; } else { // exception -- rows must be integer or double constant raiseValidateError("In rand statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } } else { // handle general expression colsExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression colsExpr.validateExpression(ids, currConstVars, conditional); } /////////////////////////////////////////////////////////////////// // HANDLE MIN /////////////////////////////////////////////////////////////////// Expression minExpr = getVarParam(RAND_MIN); // perform constant propogation if (minExpr instanceof DataIdentifier && !(minExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)minExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // update min expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); minExpr = new DoubleIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_MIN, minExpr); } // handle double constant else if (constValue instanceof DoubleIdentifier){ // update col expr with new IntIdentifier (rounded down) double roundedValue = ((DoubleIdentifier)constValue).getValue(); minExpr = new DoubleIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_MIN, minExpr); } else { // exception -- rows must be integer or double constant raiseValidateError("In rand statement, can only assign min a numerical " + "value -- attempted to assign: " + constValue.toString(), conditional); } } else { // handle general expression minExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression minExpr.validateExpression(ids, currConstVars, conditional); } /////////////////////////////////////////////////////////////////// // HANDLE MAX /////////////////////////////////////////////////////////////////// Expression maxExpr = getVarParam(RAND_MAX); // perform constant propogation if (maxExpr instanceof DataIdentifier && !(maxExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)maxExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // update min expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); maxExpr = new DoubleIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_MAX, maxExpr); } // handle double constant else if (constValue instanceof DoubleIdentifier){ // update col expr with new IntIdentifier (rounded down) double roundedValue = ((DoubleIdentifier)constValue).getValue(); maxExpr = new DoubleIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_MAX, maxExpr); } else { // exception -- rows must be integer or double constant raiseValidateError("In rand statement, can only assign max a numerical " + "value -- attempted to assign: " + constValue.toString(), conditional); } } else { // handle general expression maxExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression maxExpr.validateExpression(ids, currConstVars, conditional); } getOutput().setFormatType(FormatType.BINARY); getOutput().setDataType(DataType.MATRIX); getOutput().setValueType(ValueType.DOUBLE); getOutput().setDimensions(rowsLong, colsLong); if (getOutput() instanceof IndexedIdentifier){ // process the "target" being indexed DataIdentifier targetAsSeen = ids.get(((DataIdentifier)getOutput()).getName()); if (targetAsSeen == null){ raiseValidateError("cannot assign value to indexed identifier " + ((DataIdentifier)getOutput()).getName() + " without first initializing " + ((DataIdentifier)getOutput()).getName(), conditional); } //_output.setProperties(targetAsSeen); ((IndexedIdentifier) getOutput()).setOriginalDimensions(targetAsSeen.getDim1(), targetAsSeen.getDim2()); //((IndexedIdentifier) getOutput()).setOriginalDimensions(getOutput().getDim1(), getOutput().getDim2()); } //getOutput().computeDataType(); if (getOutput() instanceof IndexedIdentifier){ LOG.warn(this.printWarningLocation() + "Output for Rand Statement may have incorrect size information"); } break; case MATRIX: //handle default and input arguments setMatrixDefault(); for( String key : _varParams.keySet() ) { boolean found = false; for (String name : MATRIX_VALID_PARAM_NAMES) { found |= name.equals(key); } if( !found ) { raiseValidateError("unexpected parameter \"" + key + "\". " + "Legal parameters for matrix statement are (case-sensitive): " + RAND_DATA + ", " + RAND_ROWS + ", " + RAND_COLS + ", " + RAND_BY_ROW, conditional); } } //validate correct value types if (getVarParam(RAND_DATA) != null && (getVarParam(RAND_DATA) instanceof BooleanIdentifier)){ raiseValidateError("for matrix statement " + RAND_DATA + " has incorrect value type", conditional); } if (getVarParam(RAND_ROWS) != null && (getVarParam(RAND_ROWS) instanceof StringIdentifier || getVarParam(RAND_ROWS) instanceof BooleanIdentifier)){ raiseValidateError("for matrix statement " + RAND_ROWS + " has incorrect value type", conditional); } if (getVarParam(RAND_COLS) != null && (getVarParam(RAND_COLS) instanceof StringIdentifier || getVarParam(RAND_COLS) instanceof BooleanIdentifier)){ raiseValidateError("for matrix statement " + RAND_COLS + " has incorrect value type", conditional); } if ( !(getVarParam(RAND_BY_ROW) instanceof BooleanIdentifier)) { raiseValidateError("for matrix statement " + RAND_BY_ROW + " has incorrect value type", conditional); } //validate general data expression getVarParam(RAND_DATA).validateExpression(ids, currConstVars, conditional); rowsLong = -1L; colsLong = -1L; /////////////////////////////////////////////////////////////////// // HANDLE ROWS /////////////////////////////////////////////////////////////////// rowsExpr = getVarParam(RAND_ROWS); if (rowsExpr != null){ if (rowsExpr instanceof IntIdentifier) { if (((IntIdentifier)rowsExpr).getValue() >= 1 ) { rowsLong = ((IntIdentifier)rowsExpr).getValue(); } else { raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + ((IntIdentifier)rowsExpr).getValue(), conditional); } } else if (rowsExpr instanceof DoubleIdentifier) { if (((DoubleIdentifier)rowsExpr).getValue() >= 1 ) { rowsLong = Double.valueOf((Math.floor(((DoubleIdentifier)rowsExpr).getValue()))).longValue(); } else { raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + rowsExpr.toString(), conditional); } } else if (rowsExpr instanceof DataIdentifier && !(rowsExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)rowsExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // check rows is >= 1 --- throw exception if (((IntIdentifier)constValue).getValue() < 1){ raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update row expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); rowsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_ROWS, rowsExpr); rowsLong = roundedValue; } // handle double constant else if (constValue instanceof DoubleIdentifier){ if (((DoubleIdentifier)constValue).getValue() < 1.0){ raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update row expr with new IntIdentifier (rounded down) long roundedValue = Double.valueOf(Math.floor(((DoubleIdentifier)constValue).getValue())).longValue(); rowsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_ROWS, rowsExpr); rowsLong = roundedValue; } else { // exception -- rows must be integer or double constant raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } } else { // handle general expression rowsExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression rowsExpr.validateExpression(ids, currConstVars, conditional); } } /////////////////////////////////////////////////////////////////// // HANDLE COLUMNS /////////////////////////////////////////////////////////////////// colsExpr = getVarParam(RAND_COLS); if (colsExpr != null){ if (colsExpr instanceof IntIdentifier) { if (((IntIdentifier)colsExpr).getValue() >= 1 ) { colsLong = ((IntIdentifier)colsExpr).getValue(); } else { raiseValidateError("In matrix statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString(), conditional); } } else if (colsExpr instanceof DoubleIdentifier) { if (((DoubleIdentifier)colsExpr).getValue() >= 1 ) { colsLong = Double.valueOf((Math.floor(((DoubleIdentifier)colsExpr).getValue()))).longValue(); } else { raiseValidateError("In matrix statement, can only assign rows a long " + "(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString(), conditional); } } else if (colsExpr instanceof DataIdentifier && !(colsExpr instanceof IndexedIdentifier)) { // check if the DataIdentifier variable is a ConstIdentifier String identifierName = ((DataIdentifier)colsExpr).getName(); if (currConstVars.containsKey(identifierName)){ // handle int constant ConstIdentifier constValue = currConstVars.get(identifierName); if (constValue instanceof IntIdentifier){ // check cols is >= 1 --- throw exception if (((IntIdentifier)constValue).getValue() < 1){ raiseValidateError("In matrix statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update col expr with new IntIdentifier long roundedValue = ((IntIdentifier)constValue).getValue(); colsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_COLS, colsExpr); colsLong = roundedValue; } // handle double constant else if (constValue instanceof DoubleIdentifier){ if (((DoubleIdentifier)constValue).getValue() < 1){ raiseValidateError("In matrix statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } // update col expr with new IntIdentifier (rounded down) long roundedValue = Double.valueOf(Math.floor(((DoubleIdentifier)constValue).getValue())).longValue(); colsExpr = new IntIdentifier(roundedValue, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); addVarParam(RAND_COLS, colsExpr); colsLong = roundedValue; } else { // exception -- rows must be integer or double constant raiseValidateError("In matrix statement, can only assign cols a long " + "(integer) value >= 1 -- attempted to assign value: " + constValue.toString(), conditional); } } else { // handle general expression colsExpr.validateExpression(ids, currConstVars, conditional); } } else { // handle general expression colsExpr.validateExpression(ids, currConstVars, conditional); } } getOutput().setFormatType(FormatType.BINARY); getOutput().setDataType(DataType.MATRIX); getOutput().setValueType(ValueType.DOUBLE); getOutput().setDimensions(rowsLong, colsLong); if (getOutput() instanceof IndexedIdentifier){ ((IndexedIdentifier) getOutput()).setOriginalDimensions(getOutput().getDim1(), getOutput().getDim2()); } //getOutput().computeDataType(); if (getOutput() instanceof IndexedIdentifier){ LOG.warn(this.printWarningLocation() + "Output for matrix Statement may have incorrect size information"); } break; default: raiseValidateError("Unsupported Data expression"+ this.getOpCode(), false, LanguageErrorCodes.INVALID_PARAMETERS); //always unconditional } return; } private void performConstantPropagationRand( HashMap<String, ConstIdentifier> currConstVars ) { //here, we propagate constants for all rand parameters that are required during validate. String[] paramNamesForEval = new String[]{RAND_DATA, RAND_SPARSITY, RAND_MIN, RAND_MAX}; //replace data identifiers with const identifiers performConstantPropagation(currConstVars, paramNamesForEval); } private void performConstantPropagationReadWrite( HashMap<String, ConstIdentifier> currConstVars ) { //here, we propagate constants for all read/write parameters that are required during validate. String[] paramNamesForEval = new String[]{FORMAT_TYPE, IO_FILENAME, READROWPARAM, READCOLPARAM, READNUMNONZEROPARAM}; //replace data identifiers with const identifiers performConstantPropagation(currConstVars, paramNamesForEval); } private void performConstantPropagation( HashMap<String, ConstIdentifier> currConstVars, String[] paramNames ) { for( String paramName : paramNames ) { Expression paramExp = getVarParam(paramName); if ( paramExp != null && paramExp instanceof DataIdentifier && !(paramExp instanceof IndexedIdentifier) && currConstVars.containsKey(((DataIdentifier) paramExp).getName())) { addVarParam(paramName, currConstVars.get(((DataIdentifier)paramExp).getName())); } } } private String fileNameCat(BinaryExpression expr, HashMap<String, ConstIdentifier> currConstVars, String filename, boolean conditional) throws LanguageException { // Processing the left node first if (expr.getLeft() instanceof BinaryExpression && ((BinaryExpression)expr.getLeft()).getKind()== BinaryExpression.Kind.BinaryOp && ((BinaryExpression)expr.getLeft()).getOpCode() == BinaryOp.PLUS){ filename = fileNameCat((BinaryExpression)expr.getLeft(), currConstVars, filename, conditional)+ filename; } else if (expr.getLeft() instanceof ConstIdentifier){ filename = ((ConstIdentifier)expr.getLeft()).toString()+ filename; } else if (expr.getLeft() instanceof DataIdentifier && ((DataIdentifier)expr.getLeft()).getDataType() == Expression.DataType.SCALAR && ((DataIdentifier)expr.getLeft()).getKind() == Expression.Kind.Data){ //&& ((DataIdentifier)expr.getLeft()).getValueType() == Expression.ValueType.STRING){ String name = ((DataIdentifier)expr.getLeft()).getName(); filename = ((StringIdentifier)currConstVars.get(name)).getValue() + filename; } else { raiseValidateError("Parameter " + IO_FILENAME + " only supports a const string or const string concatenations.", conditional); } // Now process the right node if (expr.getRight()instanceof BinaryExpression && ((BinaryExpression)expr.getRight()).getKind()== BinaryExpression.Kind.BinaryOp && ((BinaryExpression)expr.getRight()).getOpCode() == BinaryOp.PLUS){ filename = filename + fileNameCat((BinaryExpression)expr.getRight(), currConstVars, filename, conditional); } // DRB: CHANGE else if (expr.getRight() instanceof ConstIdentifier){ filename = filename + ((ConstIdentifier)expr.getRight()).toString(); } else if (expr.getRight() instanceof DataIdentifier && ((DataIdentifier)expr.getRight()).getDataType() == Expression.DataType.SCALAR && ((DataIdentifier)expr.getRight()).getKind() == Expression.Kind.Data && ((DataIdentifier)expr.getRight()).getValueType() == Expression.ValueType.STRING){ String name = ((DataIdentifier)expr.getRight()).getName(); filename = filename + ((StringIdentifier)currConstVars.get(name)).getValue(); } else { raiseValidateError("Parameter " + IO_FILENAME + " only supports a const string or const string concatenations.", conditional); } return filename; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(_opcode.toString()); sb.append("("); for(Entry<String,Expression> e : _varParams.entrySet()) { String key = e.getKey(); Expression expr = e.getValue(); sb.append(","); sb.append(key); sb.append("="); sb.append(expr); } sb.append(" )"); return sb.toString(); } @Override public VariableSet variablesRead() { VariableSet result = new VariableSet(); for( Expression expr : _varParams.values() ) { result.addVariables ( expr.variablesRead() ); } return result; } @Override public VariableSet variablesUpdated() { VariableSet result = new VariableSet(); for( Expression expr : _varParams.values() ) { result.addVariables ( expr.variablesUpdated() ); } result.addVariable(((DataIdentifier)this.getOutput()).getName(), (DataIdentifier)this.getOutput()); return result; } @SuppressWarnings("unchecked") private void parseMetaDataFileParameters(String mtdFileName, JSONObject configObject, boolean conditional) throws LanguageException { for( Object obj : configObject.entrySet() ){ Entry<Object,Object> e = (Entry<Object, Object>) obj; Object key = e.getKey(); Object val = e.getValue(); boolean isValidName = false; for (String paramName : READ_VALID_MTD_PARAM_NAMES){ if (paramName.equals(key)) isValidName = true; } if (!isValidName){ //wrong parameters always rejected raiseValidateError("MTD file " + mtdFileName + " contains invalid parameter name: " + key, false); } // if the read method parameter is a constant, then verify value matches MTD metadata file if (getVarParam(key.toString()) != null && (getVarParam(key.toString()) instanceof ConstIdentifier) && !getVarParam(key.toString()).toString().equalsIgnoreCase(val.toString()) ) { raiseValidateError("parameter " + key.toString() + " has conflicting values in read statement definition and metadata. " + "Config file value: " + val.toString() + " from MTD file. Read statement value: " + getVarParam(key.toString()), conditional); } else { // if the read method does not specify parameter value, then add MTD metadata file value to parameter list if (getVarParam(key.toString()) == null){ if ( !key.toString().equalsIgnoreCase(DESCRIPTIONPARAM) ) { StringIdentifier strId = new StringIdentifier(val.toString(), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); if ( key.toString().equalsIgnoreCase(DELIM_HAS_HEADER_ROW) || key.toString().equalsIgnoreCase(DELIM_FILL) || key.toString().equalsIgnoreCase(DELIM_SPARSE) ) { // parse these parameters as boolean values BooleanIdentifier boolId = null; if ( strId.toString().equalsIgnoreCase("true") ) { boolId = new BooleanIdentifier(true, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); } else if ( strId.toString().equalsIgnoreCase("false") ) { boolId = new BooleanIdentifier(false, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); } else { raiseValidateError("Invalid value provided for '" + DELIM_HAS_HEADER_ROW + "' in metadata file '" + mtdFileName + "'. " + "Must be either TRUE or FALSE.", conditional); } removeVarParam(key.toString()); addVarParam(key.toString(), boolId); } else if ( key.toString().equalsIgnoreCase(DELIM_FILL_VALUE)) { // parse these parameters as numeric values DoubleIdentifier doubleId = new DoubleIdentifier( Double.parseDouble(strId.toString()), this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); removeVarParam(key.toString()); addVarParam(key.toString(), doubleId); } else if (key.toString().equalsIgnoreCase(DELIM_NA_STRINGS)) { String naStrings = null; if ( val instanceof String) { naStrings = val.toString(); } else { StringBuilder sb = new StringBuilder(); JSONArray valarr = (JSONArray)val; for(int naid=0; naid < valarr.size(); naid++ ) { sb.append( (String) valarr.get(naid) ); if ( naid < valarr.size()-1) sb.append( DELIM_NA_STRING_SEP ); } naStrings = sb.toString(); } StringIdentifier sid = new StringIdentifier( naStrings, this.getFilename(), this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); removeVarParam(key.toString()); addVarParam(key.toString(), sid); } else { // by default, treat a parameter as a string addVarParam(key.toString(), strId); } } } } } } public JSONObject readMetadataFile(String filename, boolean conditional) throws LanguageException { JSONObject retVal = null; boolean exists = false; FileSystem fs = null; try { fs = FileSystem.get(ConfigurationManager.getCachedJobConf()); } catch (Exception e){ raiseValidateError("could not read the configuration file: "+e.getMessage(), false); } Path pt = new Path(filename); try { if (fs.exists(pt)){ exists = true; } } catch (Exception e){ exists = false; } boolean isDirBoolean = false; try { if (exists && fs.getFileStatus(pt).isDirectory()) isDirBoolean = true; else isDirBoolean = false; } catch(Exception e){ raiseValidateError("error validing whether path " + pt.toString() + " is directory or not: "+e.getMessage(), conditional); } // CASE: filename is a directory -- process as a directory if (exists && isDirBoolean){ // read directory contents retVal = new JSONObject(); FileStatus[] stats = null; try { stats = fs.listStatus(pt); } catch (Exception e){ raiseValidateError("for MTD file in directory, error reading directory with MTD file " + pt.toString() + ": " + e.getMessage(), conditional); } for(FileStatus stat : stats){ Path childPath = stat.getPath(); // gives directory name if (childPath.getName().startsWith("part")){ BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.open(childPath))); } catch(Exception e){ raiseValidateError("for MTD file in directory, error reading part of MTD file with path " + childPath.toString() + ": " + e.getMessage(), conditional); } JSONObject childObj = null; try { childObj = JSONHelper.parse(br); } catch(Exception e){ raiseValidateError("for MTD file in directory, error parsing part of MTD file with path " + childPath.toString() + ": " + e.getMessage(), conditional); } for( Object obj : childObj.entrySet() ){ @SuppressWarnings("unchecked") Entry<Object,Object> e = (Entry<Object, Object>) obj; Object key = e.getKey(); Object val = e.getValue(); retVal.put(key, val); } } } // end for } // CASE: filename points to a file else if (exists){ BufferedReader br = null; // try reading MTD file try { br=new BufferedReader(new InputStreamReader(fs.open(pt))); } catch (Exception e){ raiseValidateError("error reading MTD file with path " + pt.toString() + ": " + e.getMessage(), conditional); } // try parsing MTD file try { retVal = JSONHelper.parse(br); } catch (Exception e){ raiseValidateError("error parsing MTD file with path " + pt.toString() + ": " + e.getMessage(), conditional); } } return retVal; } public String[] readMatrixMarketFile(String filename, boolean conditional) throws LanguageException { String[] retVal = new String[2]; retVal[0] = new String(""); retVal[1] = new String(""); boolean exists = false; try { FileSystem fs = FileSystem.get(ConfigurationManager.getCachedJobConf()); Path pt = new Path(filename); if (fs.exists(pt)){ exists = true; } boolean getFileStatusIsDir = fs.getFileStatus(pt).isDirectory(); if (exists && getFileStatusIsDir){ raiseValidateError("MatrixMarket files as directories not supported", conditional); } else if (exists) { BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(pt))); try { retVal[0] = in.readLine(); // skip all commented lines do { retVal[1] = in.readLine(); } while ( retVal[1].charAt(0) == '%' ); if ( !retVal[0].startsWith("%%") ) { raiseValidateError("MatrixMarket files must begin with a header line.", conditional); } } finally { if( in != null ) in.close(); } } else { raiseValidateError("Could not find the file: " + filename, conditional); } } catch (IOException e){ //LOG.error(this.printErrorLocation() + "Error reading MatrixMarket file: " + filename ); //throw new LanguageException(this.printErrorLocation() + "Error reading MatrixMarket file: " + filename ); throw new LanguageException(e); } return retVal; } public boolean checkHasMatrixMarketFormat(String inputFileName, String mtdFileName, boolean conditional) throws LanguageException { // Check the MTD file exists. if there is an MTD file, return false. JSONObject mtdObject = readMetadataFile(mtdFileName, conditional); if (mtdObject != null) return false; boolean exists = false; FileSystem fs = null; try { fs = FileSystem.get(ConfigurationManager.getCachedJobConf()); } catch (Exception e){ LOG.error(this.printErrorLocation() + "could not read the configuration file."); throw new LanguageException(this.printErrorLocation() + "could not read the configuration file.", e); } Path pt = new Path(inputFileName); try { if (fs.exists(pt)){ exists = true; } } catch (Exception e){ LOG.error(this.printErrorLocation() + "file " + inputFileName + " not found"); throw new LanguageException(this.printErrorLocation() + "file " + inputFileName + " not found"); } try { // CASE: filename is a directory -- process as a directory if (exists && fs.getFileStatus(pt).isDirectory()){ // currently, only MM files as files are supported. So, if file is directory, then infer // likely not MM file return false; } // CASE: filename points to a file else if (exists){ //BufferedReader in = new BufferedReader(new FileReader(filename)); BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(pt))); String headerLine = new String(""); if (in.ready()) headerLine = in.readLine(); in.close(); // check that headerline starts with "%%" // will infer malformed if( headerLine !=null && headerLine.startsWith("%%") ) return true; else return false; } else { return false; } } catch (Exception e){ return false; } } public boolean checkHasDelimitedFormat(String filename, boolean conditional) throws LanguageException { // if the MTD file exists, check the format is not binary JSONObject mtdObject = readMetadataFile(filename + ".mtd", conditional); if (mtdObject != null){ String formatTypeString = (String)JSONHelper.get(mtdObject,FORMAT_TYPE); if (formatTypeString != null ) { if ( formatTypeString.equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV) ) return true; else return false; } } return false; // The file format must be specified either in .mtd file or in read() statement // Therefore, one need not actually read the data to infer the format. } public boolean isCSVReadWithUnknownSize() { boolean ret = false; Expression format = getVarParam(FORMAT_TYPE); if( _opcode == DataOp.READ && format!=null && format.toString().equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV) ) { Expression rows = getVarParam(READROWPARAM); Expression cols = getVarParam(READCOLPARAM); if( (rows==null || Long.parseLong(rows.toString())<0) ||(cols==null || Long.parseLong(cols.toString())<0) ) { ret = true; } } return ret; } public boolean isRead() { return (_opcode == DataOp.READ); } } // end class
package com.sofkau.practice2.configuration; import org.modelmapper.ModelMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Practice2Configuration { @Bean public ModelMapper modelMapper() { return new ModelMapper(); } }
package ca.jvsh.networkbenchmark; import java.io.IOException; import java.io.InputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Collections; import java.util.List; import org.apache.http.conn.util.InetAddressUtils; import com.actionbarsherlock.app.SherlockFragment; import android.content.Context; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class ServerFragment extends SherlockFragment { private EditText mServerOpenPortEdit; private ToggleButton mServerOnOffToggleButton; private Button mZeroBytesButton; private TextView mBytesReceivedTextView; private TextView mIpTextView; private RadioGroup mSocketTypeRadioGroup; private Context mContext; private int mReadBytes; private int mReadBytesTotal; private byte[] mDataBuffer = new byte[30000]; private InputStream mInputStream; private static boolean mActive = false; private Thread mServerThread; private ServerSocket mServerTcpSocket = null; DatagramSocket mServerUdpSocket = null; private int mServerPort; // Debugging tag. private static final String TAG = "ServerFragment"; protected static final int MSG_SERVER_SOCKET_ERR = 0; protected static final int MSG_BYTES_RECEIVED = 1; /** * Create a new instance of CountingFragment, providing "num" * as an argument. */ static ServerFragment newInstance(int num) { return new ServerFragment(); } /** * The Fragment's UI is just a simple text view showing its * instance number. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_server, container, false); mContext = view.getContext(); //set ip { mIpTextView = (TextView) (view.findViewById(R.id.ip)); String ip = ServerFragment.getLocalIpAddress(mContext); if (ip == null) { mIpTextView.setText("No Internet connection"); } else { mIpTextView.setText("My ip is " + ip); } } mServerOpenPortEdit = (EditText) view.findViewById(R.id.editTextPort); mBytesReceivedTextView = (TextView) view.findViewById(R.id.textViewBytesReceived); mServerOnOffToggleButton = (ToggleButton) view.findViewById(R.id.serverSocketButton); mServerOnOffToggleButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mServerOnOffToggleButton.isChecked()) { if (!socketStart()) mServerOnOffToggleButton.setChecked(false); } else { socketStop(); } } }); mZeroBytesButton = (Button) view.findViewById(R.id.serverZeroBytesButton); mZeroBytesButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Message m = new Message(); m.what = MSG_BYTES_RECEIVED; m.arg1 = mReadBytesTotal = 0; mToastHandler.sendMessage(m); } }); //restore port that server will open mServerOpenPortEdit.setText(PreferenceManager.getDefaultSharedPreferences(mContext).getString("server_open_port", "6000")); //restore server socket type mSocketTypeRadioGroup = (RadioGroup) view.findViewById(R.id.radioGroupServer); mSocketTypeRadioGroup.check(PreferenceManager.getDefaultSharedPreferences(mContext).getInt("server_socket_type", R.id.radioServerTcp)); return view; } @Override public void onResume() { super.onResume(); if (mContext == null) mIpTextView.setText("No Internet connection"); else { String ip = ServerFragment.getLocalIpAddress(mContext); if (ip == null) { mIpTextView.setText("No Internet connection"); } else { mIpTextView.setText("My ip is " + ip); } } } @Override public void onStop() { ////////////////////////////////// //saving parameters ////////////////////////////////// Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); //save port that server would open editor.putString("server_open_port", mServerOpenPortEdit.getText().toString()); editor.putInt("server_socket_type", mSocketTypeRadioGroup.getCheckedRadioButtonId()); editor.commit(); //stop client threads super.onStop(); } protected boolean socketStart() { //test socket switch (mSocketTypeRadioGroup.getCheckedRadioButtonId()) { case R.id.radioServerTcp: return socketTcpStart(); case R.id.radioServerUdp: return socketUdpStart(); } return false; } protected boolean socketTcpStart() { //check if we have something in the port edit try { mServerPort = Integer.parseInt(mServerOpenPortEdit.getText().toString()); } catch (NumberFormatException ex) { Log.d(TAG, "Can't read port number"); ex.printStackTrace(); Toast.makeText(mContext, "Can't read port number", Toast.LENGTH_SHORT).show(); return false; } mReadBytesTotal = 0; mBytesReceivedTextView.setText("0"); mActive = true; mServerThread = new Thread() { public void run() { try { mServerTcpSocket = new ServerSocket(mServerPort); } catch (IOException ex) { Log.d(TAG, "Can't open server socket"); ex.printStackTrace(); Message m = new Message(); m.what = MSG_SERVER_SOCKET_ERR; mToastHandler.sendMessage(m); mActive = false; mServerThread = null; return; } Socket s = null; while (mActive) { try { if (s == null) s = mServerTcpSocket.accept(); mInputStream = s.getInputStream(); while ((mReadBytes = mInputStream.read(mDataBuffer)) > 0) { mReadBytesTotal += mReadBytes; } Message m = new Message(); m.what = MSG_BYTES_RECEIVED; m.arg1 = mReadBytesTotal; mToastHandler.sendMessage(m); s.close(); s = null; } catch (IOException e) { e.printStackTrace(); } } } }; mServerThread.start(); return true; } protected boolean socketUdpStart() { try { mServerPort = Integer.parseInt(mServerOpenPortEdit.getText().toString()); } catch (NumberFormatException ex) { Log.d(TAG, "Can't read port number"); ex.printStackTrace(); Toast.makeText(mContext, "Can't read port number", Toast.LENGTH_SHORT).show(); return false; } mReadBytesTotal = 0; mBytesReceivedTextView.setText("0"); mActive = true; mServerThread = new Thread() { public void run() { try { mServerUdpSocket = new DatagramSocket(mServerPort); } catch (SocketException ex) { Log.d(TAG, "Can't open server socket"); ex.printStackTrace(); Message m = new Message(); m.what = MSG_SERVER_SOCKET_ERR; mToastHandler.sendMessage(m); mActive = false; mServerThread = null; return; } while (mActive) { try { DatagramPacket receivePacket = new DatagramPacket(mDataBuffer, mDataBuffer.length); mServerUdpSocket.receive(receivePacket); mReadBytesTotal += receivePacket.getLength(); ; Message m = new Message(); m.what = MSG_BYTES_RECEIVED; m.arg1 = mReadBytesTotal; mToastHandler.sendMessage(m); } catch (IOException e) { e.printStackTrace(); } } } }; mServerThread.start(); return true; } protected void socketStop() { //test socket switch (mSocketTypeRadioGroup.getCheckedRadioButtonId()) { case R.id.radioServerTcp: socketTcpStop(); break; case R.id.radioServerUdp: socketUdpStop(); break; } } protected void socketTcpStop() { mActive = false; mServerThread = null; if (mServerTcpSocket != null) if (!mServerTcpSocket.isClosed()) try { mServerTcpSocket.close(); } catch (IOException e) { e.printStackTrace(); } } protected void socketUdpStop() { mActive = false; mServerThread = null; if (mServerUdpSocket != null) if (!mServerUdpSocket.isClosed()) mServerUdpSocket.close(); } public static String getLocalIpAddress(Context context) { try { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); //try get wifi address first if (wifi.isAvailable()) { WifiManager myWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); int ipAddress = myWifiInfo.getIpAddress(); return intToIp(ipAddress); } //if no success use that standard way String ipv4; List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface ni : nilist) { //display only connections that are up if (ni.isUp()) { List<InetAddress> ialist = Collections.list(ni.getInetAddresses()); for (InetAddress address : ialist) { if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress())) { return ipv4; } } } } } catch (SocketException ex) { Log.e("ClientSocketActivity", ex.toString()); } return null; } public static String intToIp(int ip) { return String.format( "%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff)); } Handler mToastHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MSG_SERVER_SOCKET_ERR: Toast.makeText(mContext, "Can't open server socket", Toast.LENGTH_SHORT).show(); mServerOnOffToggleButton.setChecked(false); break; case MSG_BYTES_RECEIVED: mBytesReceivedTextView.setText(" " + msg.arg1); default: break; } super.handleMessage(msg); } }; }
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.model.migration; import java.util.Arrays; import java.util.Date; import java.util.GregorianCalendar; import org.talend.commons.ui.runtime.exception.ExceptionHandler; import org.talend.core.model.components.ComponentUtilities; import org.talend.core.model.components.ModifyComponentsAction; import org.talend.core.model.components.conversions.IComponentConversion; import org.talend.core.model.components.filters.IComponentFilter; import org.talend.core.model.components.filters.NameComponentFilter; import org.talend.core.model.migration.AbstractJobMigrationTask; import org.talend.core.model.properties.Item; import org.talend.designer.core.model.utils.emf.talendfile.ElementParameterType; import org.talend.designer.core.model.utils.emf.talendfile.NodeType; import org.talend.designer.core.model.utils.emf.talendfile.ProcessType; /** * rdubois class global comment. Detailled comment */ public class ReplaceHostAndPortByNamenodeURIMigrationTask extends AbstractJobMigrationTask { @Override public ExecutionResult execute(Item item) { try { replaceHostAndPort(item); return ExecutionResult.SUCCESS_NO_ALERT; } catch (Exception e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } } public Date getOrder() { GregorianCalendar gc = new GregorianCalendar(2012, 7, 27, 16, 45, 0); return gc.getTime(); } private void replaceHostAndPort(Item item) throws Exception { ProcessType processType = getProcessType(item); java.util.List<IComponentFilter> filters = new java.util.ArrayList<IComponentFilter>(); filters.add(new NameComponentFilter("tHDFSPut")); filters.add(new NameComponentFilter("tHDFSGet")); filters.add(new NameComponentFilter("tHDFSRename")); IComponentConversion addNNUri = new AddNNUri(); java.util.Iterator<IComponentFilter> iter = filters.iterator(); while (iter.hasNext()) { IComponentFilter filter = (IComponentFilter) iter.next(); ModifyComponentsAction.searchAndModify(item, processType, filter, Arrays.<IComponentConversion> asList(addNNUri)); } } /** * * rdubois AddConnectionMode class global comment. Detailled comment */ private class AddNNUri implements IComponentConversion { private String field = "TEXT"; //$NON-NLS-1$ private String name = "FS_DEFAULT_NAME"; //$NON-NLS-1$ public AddNNUri() { super(); } public void transform(NodeType node) { if (ComponentUtilities.getNodeProperty(node, name) == null) { ComponentUtilities.addNodeProperty(node, name, field); } String host = "", port = ""; boolean hostDone = false, portDone = false; for (Object o : node.getElementParameter()) { ElementParameterType para = (ElementParameterType) o; if ("HOST".equals(para.getName())) { host = para.getValue(); hostDone = true; } if ("PORT".equals(para.getName())) { port = para.getValue(); portDone = true; } if (hostDone && portDone) break; } for (Object o : node.getElementParameter()) { ElementParameterType para = (ElementParameterType) o; if ("DB_VERSION".equals(para.getName())) { //$NON-NLS-1$ if (para.getValue() .startsWith("hadoop-0.20.2-dev-core.jar")) { ComponentUtilities.setNodeValue(node, name, "\"maprfs://\"+" + host + "+\":\" + " + port + " + \"/\""); } else { ComponentUtilities.setNodeValue(node, name, "\"hdfs://\"+" + host + "+\":\" + " + port); } break; } } } } }
package main.java.app.javache.http.contracts; import java.util.Map; /** * Created by George-Lenovo on 6/29/2017. */ public interface IHttpSession { Map<String, IHttpCookie> getCookies(); void addCookie(IHttpCookie cookie); void removeCookie(String userId); }
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.storemanage.service.impl; import me.zhengjie.storemanage.domain.StoreSupply; import me.zhengjie.exception.EntityExistException; import me.zhengjie.utils.ValidationUtil; import me.zhengjie.utils.FileUtil; import lombok.RequiredArgsConstructor; import me.zhengjie.storemanage.repository.StoreSupplyRepository; import me.zhengjie.storemanage.service.StoreSupplyService; import me.zhengjie.storemanage.service.dto.StoreSupplyDto; import me.zhengjie.storemanage.service.dto.StoreSupplyQueryCriteria; import me.zhengjie.storemanage.service.mapstruct.StoreSupplyMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import me.zhengjie.utils.PageUtil; import me.zhengjie.utils.QueryHelp; import java.util.List; import java.util.Map; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.LinkedHashMap; /** * @website https://el-admin.vip * @description 服务实现 * @author freebirdweij * @date 2021-02-27 **/ @Service @RequiredArgsConstructor public class StoreSupplyServiceImpl implements StoreSupplyService { private final StoreSupplyRepository storeSupplyRepository; private final StoreSupplyMapper storeSupplyMapper; @Override public Map<String,Object> queryAll(StoreSupplyQueryCriteria criteria, Pageable pageable){ Page<StoreSupply> page = storeSupplyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); return PageUtil.toPage(page.map(storeSupplyMapper::toDto)); } @Override public List<StoreSupplyDto> queryAll(StoreSupplyQueryCriteria criteria){ return storeSupplyMapper.toDto(storeSupplyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override @Transactional public StoreSupplyDto findById(Long supplyId) { StoreSupply storeSupply = storeSupplyRepository.findById(supplyId).orElseGet(StoreSupply::new); ValidationUtil.isNull(storeSupply.getSupplyId(),"StoreSupply","supplyId",supplyId); return storeSupplyMapper.toDto(storeSupply); } @Override @Transactional(rollbackFor = Exception.class) public StoreSupplyDto create(StoreSupply resources) { if(storeSupplyRepository.findBySupplyCode(resources.getSupplyCode()) != null){ throw new EntityExistException(StoreSupply.class,"supply_code",resources.getSupplyCode()); } return storeSupplyMapper.toDto(storeSupplyRepository.save(resources)); } @Override @Transactional(rollbackFor = Exception.class) public void update(StoreSupply resources) { StoreSupply storeSupply = storeSupplyRepository.findById(resources.getSupplyId()).orElseGet(StoreSupply::new); ValidationUtil.isNull( storeSupply.getSupplyId(),"StoreSupply","id",resources.getSupplyId()); StoreSupply storeSupply1 = null; storeSupply1 = storeSupplyRepository.findBySupplyCode(resources.getSupplyCode()); if(storeSupply1 != null && !storeSupply1.getSupplyId().equals(storeSupply.getSupplyId())){ throw new EntityExistException(StoreSupply.class,"supply_code",resources.getSupplyCode()); } storeSupply.copy(resources); storeSupplyRepository.save(storeSupply); } @Override public void deleteAll(Long[] ids) { for (Long supplyId : ids) { storeSupplyRepository.deleteById(supplyId); } } @Override public void download(List<StoreSupplyDto> all, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (StoreSupplyDto storeSupply : all) { Map<String,Object> map = new LinkedHashMap<>(); map.put("供应商号", storeSupply.getSupplyCode()); map.put("供应商名称", storeSupply.getName()); map.put("联系人", storeSupply.getContact()); map.put("联系电话", storeSupply.getPhone()); map.put("传真", storeSupply.getFax()); map.put("地址", storeSupply.getAddress()); map.put("邮政编码", storeSupply.getZipcode()); map.put("网址", storeSupply.getWebadd()); map.put("邮箱", storeSupply.getEmail()); map.put("创建者", storeSupply.getCreateBy()); map.put("更新者", storeSupply.getUpdateBy()); map.put("创建日期", storeSupply.getCreateTime()); map.put("更新时间", storeSupply.getUpdateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v8.services.stub; import com.google.ads.googleads.v8.resources.FeedItemTarget; import com.google.ads.googleads.v8.services.GetFeedItemTargetRequest; import com.google.ads.googleads.v8.services.MutateFeedItemTargetsRequest; import com.google.ads.googleads.v8.services.MutateFeedItemTargetsResponse; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link FeedItemTargetServiceStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li> The default service address (googleads.googleapis.com) and default port (443) are used. * <li> Credentials are acquired automatically through Application Default Credentials. * <li> Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of getFeedItemTarget to 30 seconds: * * <pre>{@code * FeedItemTargetServiceStubSettings.Builder feedItemTargetServiceSettingsBuilder = * FeedItemTargetServiceStubSettings.newBuilder(); * feedItemTargetServiceSettingsBuilder * .getFeedItemTargetSettings() * .setRetrySettings( * feedItemTargetServiceSettingsBuilder * .getFeedItemTargetSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * FeedItemTargetServiceStubSettings feedItemTargetServiceSettings = * feedItemTargetServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class FeedItemTargetServiceStubSettings extends StubSettings<FeedItemTargetServiceStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/adwords").build(); private final UnaryCallSettings<GetFeedItemTargetRequest, FeedItemTarget> getFeedItemTargetSettings; private final UnaryCallSettings<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> mutateFeedItemTargetsSettings; /** Returns the object with the settings used for calls to getFeedItemTarget. */ public UnaryCallSettings<GetFeedItemTargetRequest, FeedItemTarget> getFeedItemTargetSettings() { return getFeedItemTargetSettings; } /** Returns the object with the settings used for calls to mutateFeedItemTargets. */ public UnaryCallSettings<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> mutateFeedItemTargetsSettings() { return mutateFeedItemTargetsSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public FeedItemTargetServiceStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcFeedItemTargetServiceStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "googleads.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "googleads.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(FeedItemTargetServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected FeedItemTargetServiceStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); getFeedItemTargetSettings = settingsBuilder.getFeedItemTargetSettings().build(); mutateFeedItemTargetsSettings = settingsBuilder.mutateFeedItemTargetsSettings().build(); } /** Builder for FeedItemTargetServiceStubSettings. */ public static class Builder extends StubSettings.Builder<FeedItemTargetServiceStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<GetFeedItemTargetRequest, FeedItemTarget> getFeedItemTargetSettings; private final UnaryCallSettings.Builder< MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> mutateFeedItemTargetsSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "retry_policy_0_codes", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.UNAVAILABLE, StatusCode.Code.DEADLINE_EXCEEDED))); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(60000L)) .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); definitions.put("retry_policy_0_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); getFeedItemTargetSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); mutateFeedItemTargetsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getFeedItemTargetSettings, mutateFeedItemTargetsSettings); initDefaults(this); } protected Builder(FeedItemTargetServiceStubSettings settings) { super(settings); getFeedItemTargetSettings = settings.getFeedItemTargetSettings.toBuilder(); mutateFeedItemTargetsSettings = settings.mutateFeedItemTargetsSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getFeedItemTargetSettings, mutateFeedItemTargetsSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .getFeedItemTargetSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .mutateFeedItemTargetsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); return builder; } // NEXT_MAJOR_VER: remove 'throws Exception'. /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to getFeedItemTarget. */ public UnaryCallSettings.Builder<GetFeedItemTargetRequest, FeedItemTarget> getFeedItemTargetSettings() { return getFeedItemTargetSettings; } /** Returns the builder for the settings used for calls to mutateFeedItemTargets. */ public UnaryCallSettings.Builder<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> mutateFeedItemTargetsSettings() { return mutateFeedItemTargetsSettings; } @Override public FeedItemTargetServiceStubSettings build() throws IOException { return new FeedItemTargetServiceStubSettings(this); } } }
package com.bx.erp.test; import static org.testng.Assert.assertTrue; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Random; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.bx.erp.action.BaseAction; import com.bx.erp.action.bo.BaseBO; import com.bx.erp.model.Barcodes; import com.bx.erp.model.BaseModel; import com.bx.erp.model.CommodityType; import com.bx.erp.model.Company; import com.bx.erp.model.RetailTrade; import com.bx.erp.model.RetailTradeCommodity; import com.bx.erp.model.Vip; import com.bx.erp.model.CommodityType.EnumCommodityType; import com.bx.erp.model.RetailTrade.EnumStatusRetailTrade; import com.bx.erp.model.commodity.Commodity; import com.bx.erp.model.commodity.SubCommodity; import com.bx.erp.model.purchasing.PurchasingOrder; import com.bx.erp.model.warehousing.Warehousing; import com.bx.erp.model.warehousing.WarehousingCommodity; import com.bx.erp.util.DataSourceContextHolder; import com.bx.erp.util.DatetimeUtil; import com.bx.erp.util.GeneralUtil; import com.bx.erp.model.ErrorInfo.EnumErrorCode; @WebAppConfiguration public class RetailTradeMapperTest extends BaseMapperTest { private Random random = new Random(); /** 被退货的零售单的ID。值为-1或>0的整数 */ private int iSourceRetailTradeID = -1; public static class DataInput { private static Vip vip = null; protected static final Vip getVip() throws CloneNotSupportedException, InterruptedException { vip = new Vip(); vip.setMobile(Shared.getValidStaffPhone()); vip.setiCID(Shared.getValidICID()); Thread.sleep(1); vip.setName("Tom" + String.valueOf(System.currentTimeMillis()).substring(6)); Thread.sleep(1); vip.setEmail(String.valueOf(System.currentTimeMillis()).substring(6) + "@bx.vip"); vip.setConsumeTimes(10); vip.setConsumeAmount(100); vip.setDistrict("广州"); vip.setCategory(1); vip.setBirthday(new Date()); vip.setBonus(100); vip.setLastConsumeDatetime(new Date()); vip.setSn(""); vip.setSex(0); vip.setLogo("123456123456"); vip.setRemark("1111"); return (Vip) vip.clone(); } } @BeforeClass public void setup() { super.setup(); } @AfterClass public void tearDown() { super.tearDown(); } @Test public void createTest1() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("Create RetailTrade Test"); // RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); } @Test public void createTest2() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("SN和POSID都相同的情况直接返回该零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // Map<String, Object> params = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(params); // ... Assert.assertTrue(createEx != null && EnumErrorCode.values()[Integer.parseInt(params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_Duplicated, "创建对象失败"); } @Test public void createTest3() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("SN和POSID不相同的情况下是正常创建"); Vip vip = BaseVipTest.DataInput.getVip(); Vip vipCreate = BaseVipTest.createViaMapper(BaseBO.INVALID_CASE_ID, vip, EnumErrorCode.EC_NoError, Shared.DBName_Test); // RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setVipID(vipCreate.getID()); rt2.setAmount(100d); // 为了下面检查积分变动.单次积分最大增加1000分.1元10积分.所以设置100元 rt2.setAmountCash(100d); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // 检查会员是否正确的处理积分,消费记录等 Vip vipRetrieve1 = (Vip) BaseVipTest.retrieve1ViaMapper(vipCreate, Shared.DBName_Test); Assert.assertTrue(vipRetrieve1.getConsumeTimes() == (vipCreate.getConsumeTimes() + 1), "消费次数错误"); Assert.assertTrue(Math.abs(GeneralUtil.sub(vipRetrieve1.getConsumeAmount(), GeneralUtil.sum(vipCreate.getConsumeAmount(), localRetailTrade2.getAmount()))) < BaseModel.TOLERANCE, "消费金额不正确"); Assert.assertTrue(vipRetrieve1.getBonus() == (vipCreate.getBonus() + GeneralUtil.mul(localRetailTrade2.getAmount(), 10)), "积分变动不正确"); } @Test public void createTest4() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("iSourceID为不存在的零售单ID,返回错误码7"); RetailTrade rt3 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt3.setSourceID(99999); Map<String, Object> params3 = rt3.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt3); // DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(params3); // ... Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(params3.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_BusinessLogicNotDefined, "错误码比对不正确"); // RetailTrade rt5 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt5.setSourceID(0); // Map<String, Object> params5 = rt5.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt5); DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(params5); // Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(params5.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_BusinessLogicNotDefined, "错误码比对不正确"); } @Test public void createTest5() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("iSourceID为存在的零售单ID,进行退货操作"); Vip vip = BaseVipTest.DataInput.getVip(); Vip vipCreate = BaseVipTest.createViaMapper(BaseBO.INVALID_CASE_ID, vip, EnumErrorCode.EC_NoError, Shared.DBName_Test); // RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setVipID(vipCreate.getID()); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // vipCreate = BaseVipTest.retrieve1ViaMapper(vipCreate, Shared.DBName_Test); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // Random ran = new Random(); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setSourceID(localRetailTrade2.getID()); rt.setLocalSN(ran.nextInt(1000)); rt.setVipID(vipCreate.getID()); RetailTrade localRetailTrade3 = BaseRetailTradeTest.createRetailTrade(rt); // 创建零售退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade3, commCreate, barcodes); // Vip vipRetrieve1 = BaseVipTest.retrieve1ViaMapper(vipCreate, Shared.DBName_Test); Assert.assertTrue(vipRetrieve1.getConsumeTimes() == (vipCreate.getConsumeTimes() - 1), "会员的消费次数不正确"); Assert.assertTrue(Math.abs(GeneralUtil.sub(vipRetrieve1.getConsumeAmount(), GeneralUtil.sub(vipCreate.getConsumeAmount(), localRetailTrade3.getAmount()))) < BaseModel.TOLERANCE, "消费金额不正确"); Assert.assertTrue(vipRetrieve1.getBonus() == vipCreate.getBonus(), "退货修改了会员的积分"); } @Test public void createTest6() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("对一张退货单再次进行退货"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setSourceID(localRetailTrade.getID()); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // 创建零售退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // RetailTrade rt3 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt3.setSourceID(localRetailTrade2.getID()); Map<String, Object> createParam3 = rt3.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt3); DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(createParam3); // ... Assert.assertTrue(EnumErrorCode.values()[Integer.parseInt(createParam3.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, createParam3.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); } @Test public void createTest7() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case7:一张零售单,最多只能进行一次退货操作"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // 第一次退货 RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setSourceID(localRetailTrade.getID()); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); Assert.assertTrue((localRetailTrade.getSn() + "_1").equals(localRetailTrade2.getSn()), "创建退货单的SN码不正确"); // 创建零售退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // 第二次退货 RetailTrade rt3 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt3.setSourceID(localRetailTrade.getID()); Map<String, Object> params3 = rt3.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt3); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(params3); // ... Assert.assertTrue(createEx.size() == 0 && EnumErrorCode.values()[Integer.parseInt(params3.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, "错误码不正确"); } @Test public void createTest8() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case8:没有子商户号的公司进行零售,使用的是微信支付,错误信息:支付失败,公司的子商户号未设置!不能进行微信支付"); // Company company = new Company(); company.setID(1); company.setSubmchid(null); Map<String, Object> paramsUpdate = company.getUpdateParam(BaseBO.CASE_Company_UpdateSubmchid, company); DataSourceContextHolder.setDbName(Shared.BXDBName_Test); companyMapper.updateSubmchid(paramsUpdate); Assert.assertTrue(EnumErrorCode.EC_NoError == EnumErrorCode.values()[Integer.parseInt(paramsUpdate.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], "修改对象失败!错误信息=" + paramsUpdate.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); // RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setPaymentType(5); rt.setAmount(10d); rt.setAmountCash(3d); rt.setAmountWeChat(7d); String err = rt.checkCreate(BaseBO.INVALID_CASE_ID); Assert.assertTrue("".equals(err), err); Map<String, Object> params1 = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); // DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(params1); // ... Assert.assertTrue(EnumErrorCode.values()[Integer.parseInt(params1.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, params1.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); // 恢复公司的数据 company.setID(1); company.setSubmchid(BaseCompanyTest.nbrSubmchid); Map<String, Object> paramsUpdate1 = company.getUpdateParam(BaseBO.CASE_Company_UpdateSubmchid, company); DataSourceContextHolder.setDbName(Shared.BXDBName_Test); companyMapper.updateSubmchid(paramsUpdate1); Assert.assertTrue(EnumErrorCode.EC_NoError == EnumErrorCode.values()[Integer.parseInt(paramsUpdate1.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], "修改对象失败!错误信息=" + paramsUpdate1.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); } @Test public void createTest9() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case9: iSourceID为存在的零售单ID,但是交易时间超过一年的订单禁止退款"); Vip vip = BaseVipTest.DataInput.getVip(); Vip vipCreate = BaseVipTest.createViaMapper(BaseBO.INVALID_CASE_ID, vip, EnumErrorCode.EC_NoError, Shared.DBName_Test); // RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.YEAR, -1);// 过去一年 c.add(Calendar.DATE, -1);// 再过去一天,大于一年 rt2.setSaleDatetime(c.getTime()); rt2.setVipID(vipCreate.getID()); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // Random ran = new Random(); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setSourceID(localRetailTrade2.getID()); rt.setLocalSN(ran.nextInt(1000)); rt.setVipID(vipCreate.getID()); Map<String, Object> createParam = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(createParam); Assert.assertTrue(createEx.size() == 0 && EnumErrorCode.values()[Integer.parseInt(createParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, "错误码不正确"); } @Test public void createTest10() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case10: iSourceID为存在的零售单ID,支付宝退款金额大于零售时的支付宝支付金额"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setPaymentType(3); rt.setAmount(100d); rt.setAmountCash(50d); rt.setAmountAlipay(50d); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, -1);// 过去一天 rt.setSaleDatetime(c.getTime()); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // Random ran = new Random(); RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setPaymentType(3); rt2.setAmount(100d); rt2.setAmountCash(40d); rt2.setAmountAlipay(60d); rt2.setSourceID(localRetailTrade.getID()); rt2.setLocalSN(ran.nextInt(1000)); Map<String, Object> createParam = rt2.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt2); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(createParam); Assert.assertTrue(createEx.size() == 0 && EnumErrorCode.values()[Integer.parseInt(createParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); Assert.assertTrue(createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).equals("退款失败,支付宝退款金额不能比零售时支付宝支付的金额多"), "错误信息不正确"); } @Test public void createTest11() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case11: iSourceID为存在的零售单ID,微信退款金额大于零售时的微信金额"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setPaymentType(5); rt.setAmount(100d); rt.setAmountCash(50d); rt.setAmountWeChat(50d); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, -1);// 过去一天 rt.setSaleDatetime(c.getTime()); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // Random ran = new Random(); RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setPaymentType(5); rt2.setAmount(100d); rt2.setAmountCash(40d); rt2.setAmountWeChat(60d); rt2.setSourceID(localRetailTrade.getID()); rt2.setLocalSN(ran.nextInt(1000)); Map<String, Object> createParam = rt2.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt2); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(createParam); Assert.assertTrue(createEx.size() == 0 && EnumErrorCode.values()[Integer.parseInt(createParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); Assert.assertTrue(createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).equals("退款失败,微信退款金额不能比零售时微信支付的金额多"), "错误信息不正确"); } @Test public void createTest12() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case12: sn为24位普通零售单,且格式正确,结果通过。"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); // rt.setSn("LS2099083000110100011234"); BaseRetailTradeTest.createRetailTrade(rt); } @Test public void createTest13() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case13: sn为26位的退货单,结尾为_1,且格式正确,结果通过。"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); // rt.setSn("LS2099083000110100011234_1"); rt.setSn(rt.getSn() + "_1"); // BaseRetailTradeTest.createRetailTrade(rt); } @Test public void createTest14() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case14: iSourceID为SQLite中的临时零售单的F_ID字段(断网情况),进行退货操作,退货成功"); // 创建零售单 RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade2, commCreate, barcodes); // 退货 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setSourceID(Shared.SOURCE_ID_OnlyFoundInSQLite); rt.setSn(localRetailTrade2.getSn() + "_1"); Map<String, Object> createParam = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(createParam); Assert.assertTrue(createEx != null && EnumErrorCode.values()[Integer.parseInt(createParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "创建对象失败"); RetailTrade localRetailTrade3 = (RetailTrade) createEx.get(0).get(0); rt.setIgnoreIDInComparision(true); rt.setSourceID(localRetailTrade3.getSourceID()); // 退货单模拟的sourceID和数据返回的正确sourceID不同,不比较 if (rt.compareTo(localRetailTrade3) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } } /** * 断网情况下,A商品已经被删除,但POS1不知道。A在POS1上售出,后来又在POS1上退货,零售单和退货单都生成并上传到后台。后台应当接受这样的零售单 */ @Test public void createTest15() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case15: 创建状态为包含已删除商品的零售单,并对其进行退货,均成功"); // 创建零售单 RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setStatus(EnumStatusRetailTrade.ESRT_IncludeDeletedCommodity.getIndex()); // checkCreate RetailTrade localRetailTrade2 = BaseRetailTradeTest.createRetailTrade(rt2); // 创建零售单商品 int deletedCommodityID = 50; RetailTradeCommodity rtc2 = BaseRetailTradeTest.DataInput.getRetailTradeCommodity(); rtc2.setCommodityID(deletedCommodityID); rtc2.setTradeID(localRetailTrade2.getID()); Map<String, Object> rtc2Params = rtc2.getCreateParam(BaseBO.INVALID_CASE_ID, rtc2); // DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTradeCommodity localRetailTradeCommodity2 = (RetailTradeCommodity) retailTradeCommodityMapper.create(rtc2Params); // ... Assert.assertTrue(localRetailTradeCommodity2 != null && EnumErrorCode.values()[Integer.parseInt(rtc2Params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, rtc2Params.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); // 由于localRetailTradeCommodity2对应的是已删除商品,数据库中的BarcodeID为NULL,但是int型的默认值是0,不会是NULL。 Assert.assertTrue(localRetailTradeCommodity2.getBarcodeID() == 0, "返回的对象的条形码有误!"); // rtc2.setIgnoreIDInComparision(true); rtc2.setBarcodeID(localRetailTradeCommodity2.getBarcodeID());// 为了让assert能通过 if (rtc2.compareTo(localRetailTradeCommodity2) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // // 创建退货单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setStatus(EnumStatusRetailTrade.ESRT_IncludeDeletedCommodity.getIndex()); rt.setSourceID(localRetailTrade2.getID()); rt.setSn(localRetailTrade2.getSn() + "_1"); // RetailTrade localRetailTrade3 = BaseRetailTradeTest.createRetailTrade(rt); // 创建退货零售单商品 RetailTradeCommodity rtc = BaseRetailTradeTest.DataInput.getRetailTradeCommodity(); rtc.setCommodityID(deletedCommodityID); rtc.setTradeID(localRetailTrade3.getID()); Map<String, Object> rtcParams = rtc.getCreateParam(BaseBO.INVALID_CASE_ID, rtc); // DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTradeCommodity localRetailTradeCommodity = (RetailTradeCommodity) retailTradeCommodityMapper.create(rtcParams); // ... Assert.assertTrue(localRetailTradeCommodity != null && EnumErrorCode.values()[Integer.parseInt(rtcParams.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, rtcParams.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); // 由于localRetailTradeCommodity2对应的是已删除商品,数据库中的BarcodeID为NULL,但是int型的默认值是0,不会是NULL。 Assert.assertTrue(localRetailTradeCommodity.getBarcodeID() == 0, "返回的对象的条形码有误!"); // rtc.setIgnoreIDInComparision(true); rtc.setBarcodeID(localRetailTradeCommodity.getBarcodeID());// 让下面的assert能通过 if (rtc.compareTo(localRetailTradeCommodity) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // 恢复rt的SourceID。在这里不需要做。 } @Test public void createTest16() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case16: VIP不存在"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setVipID(Shared.BIG_ID); // String errMsg = rt.checkCreate(BaseAction.INVALID_ID); Assert.assertEquals(errMsg, ""); // Map<String, Object> rt2Params = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(rt2Params); // ... Assert.assertTrue(EnumErrorCode.values()[Integer.parseInt(rt2Params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoSuchData, rt2Params.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); } @Test public void createTest17() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case17: POS不存在"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setPos_ID(Shared.BIG_ID); // String errMsg = rt.checkCreate(BaseAction.INVALID_ID); Assert.assertEquals(errMsg, ""); // Map<String, Object> rt2Params = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(rt2Params); // ... Assert.assertTrue(EnumErrorCode.values()[Integer.parseInt(rt2Params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoSuchData, rt2Params.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); } @Test public void createTest19() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case19: 员工不存在"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setStaffID(Shared.BIG_ID); // String errMsg = rt.checkCreate(BaseAction.INVALID_ID); Assert.assertEquals(errMsg, ""); // Map<String, Object> rt2Params = rt.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt); DataSourceContextHolder.setDbName(Shared.DBName_Test); retailTradeMapper.createEx(rt2Params); // ... Assert.assertTrue(EnumErrorCode.values()[Integer.parseInt(rt2Params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoSuchData, rt2Params.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); } @Test public void createTest20() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case20: 会员A的消费单,对其进行退货,vipID为会员B。"); // 创建会员 Vip vip = BaseVipTest.createViaMapper(BaseBO.INVALID_CASE_ID, BaseVipTest.DataInput.getVip(), EnumErrorCode.EC_NoError, Shared.DBName_Test); // 使用此会员进行消费 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setVipID(vip.getID()); // RetailTrade createRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 查询会员的消费信息 Vip vipA = BaseVipTest.retrieve1ViaMapper(vip, Shared.DBName_Test); // 进行退货,使用其他的会员ID RetailTrade returnRetailTrade = BaseRetailTradeTest.DataInput.getRetailTrade(); // 退货前,先查询传递的vipID的vip信息 Vip vipB = new Vip(); vipB.setID(returnRetailTrade.getVipID()); vipB = BaseVipTest.retrieve1ViaMapper(vipB, Shared.DBName_Test); // returnRetailTrade.setSourceID(createRetailTrade.getID()); RetailTrade createReturnRetailTrade = BaseRetailTradeTest.createRetailTrade(returnRetailTrade); // 检查是否正确的减少会员的消费 Vip afterVipA = BaseVipTest.retrieve1ViaMapper(vip, Shared.DBName_Test); Assert.assertTrue( vipA.getConsumeTimes() == afterVipA.getConsumeTimes() + 1 && Math.abs(GeneralUtil.sub(vipA.getConsumeAmount(), GeneralUtil.sum(afterVipA.getConsumeAmount(), createReturnRetailTrade.getAmount()))) < BaseModel.TOLERANCE, "会员A计算消费次数不正确"); // Vip afterVipB = BaseVipTest.retrieve1ViaMapper(vipB, Shared.DBName_Test); Assert.assertTrue(vipB.getConsumeTimes() == afterVipB.getConsumeTimes() && Math.abs(GeneralUtil.sub(vipB.getConsumeAmount(), afterVipB.getConsumeAmount())) < BaseModel.TOLERANCE, "未对会员b的单进行退货,但是会员B的消费记录却发生了改变"); } @Test public void createTest21() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case21: iSourceID为存在的零售单ID,微信和现金混合退款,大于源单的现金和微信混合支付,退款失败"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); rt.setPaymentType(5); rt.setAmount(100d); rt.setAmountCash(50d); rt.setAmountWeChat(50d); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, -1);// 过去一天 rt.setSaleDatetime(c.getTime()); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // Random ran = new Random(); RetailTrade rt2 = BaseRetailTradeTest.DataInput.getRetailTrade(); rt2.setPaymentType(5); rt2.setAmount(120d); rt2.setAmountCash(60d); rt2.setAmountWeChat(60d); rt2.setSourceID(localRetailTrade.getID()); rt2.setLocalSN(ran.nextInt(1000)); Map<String, Object> createParam = rt2.getCreateParamEx(BaseBO.INVALID_CASE_ID, rt2); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> createEx = retailTradeMapper.createEx(createParam); Assert.assertTrue(createEx.size() == 0 && EnumErrorCode.values()[Integer.parseInt(createParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_BusinessLogicNotDefined, createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).toString()); Assert.assertTrue(createParam.get(BaseAction.SP_OUT_PARAM_sErrorMsg).equals("退款失败,退款金额不能比零售时微信支付和现金支付的总金额多"), "错误信息不正确"); } @Test public void retrieveNTest1() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web请求,用最小长度(10)的零售单单号来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(retailTradeCreate.getSn().substring(0, 10)); Map<String, Object> paramsForID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : bm) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } System.out.println("根据SN来查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest2() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用localSN 和 POS_ID来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForlocalSN_ID = new RetailTrade(); rtForlocalSN_ID.setPos_ID(retailTradeCreate.getPos_ID()); rtForlocalSN_ID.setLocalSN(retailTradeCreate.getLocalSN()); Map<String, Object> paramsForlocalSN_ID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForlocalSN_ID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listlocalSN_ID = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForlocalSN_ID); Assert.assertTrue(listlocalSN_ID.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForlocalSN_ID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : listlocalSN_ID) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } System.out.println("根据localSN 和 POS_ID来查询零售单成功!" + listlocalSN_ID.toString()); } @Test public void retrieveNTest3() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用POS_ID来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForPosID = new RetailTrade(); rtForPosID.setPos_ID(retailTradeCreate.getPos_ID()); Map<String, Object> paramsForPos_ID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForPosID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listPos_ID = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForPos_ID); Assert.assertTrue(listPos_ID.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForPos_ID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : listPos_ID) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex() || retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_IncludeDeletedCommodity.getIndex()); } System.out.println("根据POS_ID来查询零售单成功!" + listPos_ID.toString()); } @Test public void retrieveNTest4() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,查询所有零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForNull = new RetailTrade(); Map<String, Object> paramsForNull = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForNull); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list2 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForNull); Assert.assertTrue(list2.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForNull.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : list2) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } System.out.println("查询所有零售单!" + list2.toString()); } @Test public void retrieveNTest5() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用时间来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtDate = new RetailTrade(); SimpleDateFormat sdf = new SimpleDateFormat(BaseAction.DATETIME_FORMAT_Default2); String string = "2017-8-6 00:00:00"; rtDate.setDatetimeStart(sdf.parse(string)); rtDate.setDatetimeEnd(new Date()); Map<String, Object> paramsDate = rtDate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtDate); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listDate = (List<BaseModel>) retailTradeMapper.retrieveN(paramsDate); Assert.assertTrue(listDate.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsDate.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : listDate) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } System.out.println("查询该期间的零售单!" + listDate.toString()); } @Test public void retrieveNTest6() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用ilocalSN来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForlocalSN_ID6 = new RetailTrade(); rtForlocalSN_ID6.setLocalSN(retailTradeCreate.getLocalSN()); Map<String, Object> paramsForlocalSN_ID6 = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForlocalSN_ID6); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listlocalSN_ID6 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForlocalSN_ID6); Assert.assertTrue(listlocalSN_ID6.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForlocalSN_ID6.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : listlocalSN_ID6) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } System.out.println("根据localSN来查询零售单成功!" + listlocalSN_ID6.toString()); } @Test public void retrieveNTest7() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用iVipID来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForVip_ID7 = new RetailTrade(); rtForVip_ID7.setVipID(retailTradeCreate.getVipID()); Map<String, Object> paramsForVip_ID7 = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForVip_ID7); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listVip_ID7 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForVip_ID7); Assert.assertTrue(listVip_ID7.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForVip_ID7.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("根据iVipID来查询零售单成功!" + listVip_ID7.toString()); } @Test public void retrieveNTest8() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用paymentType来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForPaymentType8 = new RetailTrade(); rtForPaymentType8.setPaymentType(retailTradeCreate.getPaymentType()); Map<String, Object> paramsForPaymentType8 = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForPaymentType8); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> listPaymentType8 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForPaymentType8); Assert.assertTrue(listPaymentType8.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForPaymentType8.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); boolean hasDBError = false; for (BaseModel baseModel : listPaymentType8) { RetailTrade retailTrade = (RetailTrade) baseModel; if (retailTrade.getID() == retailTradeCreate.getID()) { hasDBError = true; break; } } Assert.assertTrue(hasDBError, "查询对象失败"); System.out.println("根据paymentType来查询零售单成功!" + listPaymentType8.toString()); } @Test public void retrieveNTest9() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web端,用iStaffID来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade retailTrade = new RetailTrade(); retailTrade.setStaffID(retailTradeCreate.getStaffID()); Map<String, Object> params1 = retailTrade.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, retailTrade); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list1 = (List<BaseModel>) retailTradeMapper.retrieveN(params1); Assert.assertTrue(list1.size() > 0 && EnumErrorCode.values()[Integer.parseInt(params1.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel baseModel : list1) { RetailTrade rt1 = (RetailTrade) baseModel; assertTrue(rt1.getStaffID() == retailTrade.getStaffID()); } System.out.println("根据iStaffID来查询零售单成功!" + list1.toString()); } @Test public void retrieveNTest10() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case10: app端,用等于最大长度(26)且以LS开头、以_1结尾的零售单单号来查询退货单,期望的是查询到数据"); // 创建零售单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // 创建退货单 RetailTrade returnRetailTrade = BaseRetailTradeTest.DataInput.getRetailTrade(); returnRetailTrade.setSourceID(localRetailTrade.getID()); RetailTrade returnRetailTradeCreate = BaseRetailTradeTest.createRetailTrade(returnRetailTrade); // 创建退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(returnRetailTradeCreate, commCreate, barcodes); // RetailTrade rtForNull = new RetailTrade(); rtForNull.setQueryKeyword(returnRetailTradeCreate.getSn()); Map<String, Object> paramsForNull = localRetailTrade.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForNull); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list2 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForNull); Assert.assertTrue(list2.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForNull.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); } @Test public void retrieveNTest11() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case11: web端,使用零售单存在的商品名称进行模糊查询"); // 创建零售单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 RetailTradeCommodity retailTradeCommodityCreate = BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // 查询零售单 RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(retailTradeCommodityCreate.getCommodityName()); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.INVALID_CASE_ID, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("根据商品名称来查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest12() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case12: web端,使用零售单不存在的商品名称进行模糊查询"); // 查询零售单 RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword("不存在的商品名称"); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.INVALID_CASE_ID, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() == 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("根据商品名称来查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest13() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case13: web端,使用空串''进行模糊查询"); // 查询零售单 RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(""); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest14() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case14: web端,使用商品名称的一部分进行模糊查询"); // 创建零售单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建零售单商品 RetailTradeCommodity rtc = BaseRetailTradeTest.DataInput.getRetailTradeCommodity(); rtc.setTradeID(retailTradeCreate.getID()); rtc.setCommodityID(163); rtc.setNO(10); rtc.setOperatorStaffID(STAFF_ID1); Map<String, Object> params = rtc.getCreateParam(BaseBO.INVALID_CASE_ID, rtc); DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTradeCommodity retailTradeCommodityCreate = (RetailTradeCommodity) retailTradeCommodityMapper.create(params); // ... rtc.setIgnoreIDInComparision(true); if (rtc.compareTo(retailTradeCommodityCreate) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } Assert.assertTrue(retailTradeCommodityCreate != null && EnumErrorCode.values()[Integer.parseInt(params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "创建对象成功"); // 查询零售单 RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword("A"); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("根据商品名称来查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest15() throws CloneNotSupportedException, InterruptedException { Shared.printTestMethodStartInfo(); Shared.caseLog("case15: web端,根据商品名称传入特殊字符“_”模糊查询零售单"); // 创建商品 Commodity comm1 = BaseCommodityTest.DataInput.getCommodity(); comm1.setName("营养快_kahd" + System.currentTimeMillis()); List<List<BaseModel>> bmList = BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, comm1); Commodity commCreated = (Commodity) bmList.get(0).get(0); Barcodes barcodes = (Barcodes) bmList.get(1).get(0); // 创建零售单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建零售单商品 RetailTradeCommodity rtc = BaseRetailTradeTest.DataInput.getRetailTradeCommodity(); rtc.setTradeID(retailTradeCreate.getID()); rtc.setCommodityID(commCreated.getID()); rtc.setBarcodeID(barcodes.getID()); rtc.setNO(10); rtc.setOperatorStaffID(STAFF_ID1); Map<String, Object> params = rtc.getCreateParam(BaseBO.INVALID_CASE_ID, rtc); DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTradeCommodity retailTradeCommodityCreate = (RetailTradeCommodity) retailTradeCommodityMapper.create(params); // ... rtc.setIgnoreIDInComparision(true); if (rtc.compareTo(retailTradeCommodityCreate) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } Assert.assertTrue(retailTradeCommodityCreate != null && EnumErrorCode.values()[Integer.parseInt(params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "创建对象成功"); // 查询零售单 RetailTrade retailTrade = new RetailTrade(); retailTrade.setQueryKeyword("_"); Map<String, Object> paramsForID = retailTrade.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, retailTrade); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bmList1 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bmList1.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel bm : bmList1) { RetailTrade rt2 = (RetailTrade) bm; // // 查询当前零售订单的相关零售订单商品表 RetailTradeCommodity rtc1 = new RetailTradeCommodity(); rtc1.setTradeID(rt2.getID()); Map<String, Object> param = rtc1.getRetrieveNParam(BaseBO.INVALID_CASE_ID, rtc1); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> ls = retailTradeCommodityMapper.retrieveN(param); Assert.assertTrue(ls.size() > 0 && EnumErrorCode.values()[Integer.parseInt(param.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "创建对象成功"); // 用商品名称对比 for (BaseModel bm1 : ls) { rtc1 = (RetailTradeCommodity) bm1; Assert.assertTrue(rtc1.getCommodityName().contains(retailTrade.getQueryKeyword()), "查询商品名称没有包含_特殊字符"); } } } @Test public void retrieveNTest16() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case16: web端,excludeReturned = 0,查询出的零售单包含退货单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // 创建退货单 RetailTrade returnRetailTrade = BaseRetailTradeTest.DataInput.getRetailTrade(); returnRetailTrade.setSourceID(retailTradeCreate.getID()); RetailTrade returnRetailTradeCreate = BaseRetailTradeTest.createRetailTrade(returnRetailTrade); // 创建退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(returnRetailTradeCreate, commCreate, barcodes); // RetailTrade rtForNull = new RetailTrade(); Map<String, Object> paramsForNull = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForNull); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list2 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForNull); Assert.assertTrue(list2.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForNull.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); // 判断查询出来的零售单时候包含退货单 boolean existReturnTrade = false; for (BaseModel b1 : list2) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); if (retailTrade.getSourceID() != BaseAction.INVALID_ID) { existReturnTrade = true; } } Assert.assertTrue(existReturnTrade, "预期RN返回退货单,但没有返回退货单"); System.out.println("查询所有零售单!" + list2.toString()); } @Test public void retrieveNTest17() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case17: web端,excludeReturned = 1,查询出的零售单不包含退货单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // 创建退货单 RetailTrade returnRetailTrade = BaseRetailTradeTest.DataInput.getRetailTrade(); returnRetailTrade.setSourceID(retailTradeCreate.getID()); RetailTrade returnRetailTradeCreate = BaseRetailTradeTest.createRetailTrade(returnRetailTrade); // 创建退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(returnRetailTradeCreate, commCreate, barcodes); // RetailTrade rtForNull = new RetailTrade(); rtForNull.setExcludeReturned(1); Map<String, Object> paramsForNull = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForNull); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list2 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForNull); Assert.assertTrue(list2.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForNull.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); // 判断查询出来的零售单时候包含退货单 boolean existReturnTrade = false; for (BaseModel b1 : list2) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); if (retailTrade.getSourceID() != BaseAction.INVALID_ID) { existReturnTrade = true; } } Assert.assertTrue(!existReturnTrade, "预期RN不返回退货单,但返回了退货单"); System.out.println("查询所有零售单!" + list2.toString()); } @Test public void retrieveNTest18() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case18: app端,用等于最大长度(26)且以ls开头、以_1结尾的零售单单号来查询退货单,期望的是查询到数据"); // 创建零售单 RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade localRetailTrade = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(localRetailTrade, commCreate, barcodes); // 创建退货单 RetailTrade returnRetailTrade = BaseRetailTradeTest.DataInput.getRetailTrade(); returnRetailTrade.setSourceID(localRetailTrade.getID()); RetailTrade returnRetailTradeCreate = BaseRetailTradeTest.createRetailTrade(returnRetailTrade); // 创建退货单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(returnRetailTradeCreate, commCreate, barcodes); // RetailTrade rtForNull = new RetailTrade(); rtForNull.setQueryKeyword(returnRetailTradeCreate.getSn().toLowerCase()); Map<String, Object> paramsForNull = localRetailTrade.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForNull); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> list2 = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForNull); Assert.assertTrue(list2.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForNull.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); } @Test public void retrieveNTest19() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case19: app端,使用空串''进行模糊查询"); // 查询零售单 RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(""); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() > 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); System.out.println("查询零售单成功!" + bm.toString()); } @Test public void retrieveNTest20() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case20: app请求,用最小长度(10)的零售单单号来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(retailTradeCreate.getSn().substring(2, 12)); Map<String, Object> paramsForID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : bm) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } } @Test public void retrieveNTest21() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case21: web请求,根据日期(过去一月内)查询零售单时,获得满足需求的结果"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); // Calendar ca = Calendar.getInstance(); ca.setTime(new Date()); ca.add(Calendar.MONTH, -1); // 上个月 Date lastMonth = ca.getTime(); rt.setSaleDatetime(lastMonth); rt.setDatetimeStart(lastMonth); // RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(retailTradeCreate.getSn().substring(2, 12)); rtForID.setDatetimeStart(lastMonth); Map<String, Object> paramsForID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : bm) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } } @Test public void retrieveNTest22() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case22: web请求,根据日期(过去一周内)查询零售单时,获得满足需求的结果"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); // Date lastWeek = DatetimeUtil.getDays(new Date(), -7);// 上周 rt.setSaleDatetime(lastWeek); // RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // RetailTrade rtForID = new RetailTrade(); rtForID.setQueryKeyword(retailTradeCreate.getSn().substring(2, 12)); rtForID.setDatetimeStart(lastWeek); Map<String, Object> paramsForID = retailTradeCreate.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNFromApp, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (BaseModel b1 : bm) { RetailTrade retailTrade = (com.bx.erp.model.RetailTrade) b1; Assert.assertTrue(retailTrade.getStatus() == EnumStatusRetailTrade.ESRT_Normal.getIndex()); } } @Test public void retrieveNTest24() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("web请求,查看默认返回的数据是否降序"); RetailTrade rtForID = new RetailTrade(); Map<String, Object> paramsForID = rtForID.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNBySNFromWeb, rtForID); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bmList = (List<BaseModel>) retailTradeMapper.retrieveN(paramsForID); Assert.assertTrue(bmList.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); for (int i = 1; i < bmList.size(); i++) { assertTrue(bmList.get(i - 1).getID() > bmList.get(i).getID(), "数据返回错误(非降序)"); } } @Test public void retrieve1Test1() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog(" CASE1: 用ID来查询零售单"); RetailTrade rt = BaseRetailTradeTest.DataInput.getRetailTrade(); RetailTrade retailTradeCreate = BaseRetailTradeTest.createRetailTrade(rt); // 创建商品 Commodity commodity = BaseCommodityTest.DataInput.getCommodity(); List<List<BaseModel>> list = (List<List<BaseModel>>) BaseCommodityTest.createCommodityViaMapper(BaseBO.CASE_Commodity_CreateSingle, commodity); Commodity commCreate = (Commodity) list.get(0).get(0); Barcodes barcodes = (Barcodes) list.get(1).get(0); // 创建零售单商品 BaseRetailTradeTest.createRetailtradeCommodityViaMapper(retailTradeCreate, commCreate, barcodes); // Map<String, Object> paramsRetrieve1 = retailTradeCreate.getRetrieve1Param(BaseBO.INVALID_CASE_ID, retailTradeCreate); DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTrade retailTradeRetrieve1 = (RetailTrade) retailTradeMapper.retrieve1(paramsRetrieve1); Assert.assertTrue(retailTradeRetrieve1 != null && EnumErrorCode.values()[Integer.parseInt(paramsRetrieve1.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); if (retailTradeRetrieve1.compareTo(retailTradeCreate) != 0) { Assert.assertTrue(false, "查询出的对象的字段与DB读出的不相等"); } } @Test public void retrieve1Test2() { Shared.printTestMethodStartInfo(); Shared.caseLog("使用不存在的ID查询零售单"); RetailTrade rt = new RetailTrade(); rt.setID(BaseAction.INVALID_ID); Map<String, Object> params2 = rt.getRetrieve1Param(BaseBO.INVALID_CASE_ID, rt); DataSourceContextHolder.setDbName(Shared.DBName_Test); RetailTrade retailTradeCreate2 = (RetailTrade) retailTradeMapper.retrieve1(params2); Assert.assertTrue(retailTradeCreate2 == null && EnumErrorCode.values()[Integer.parseInt(params2.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); } @Test public void retrieveNByCommodityNameInTimeRangeTest1() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case1:正常查询,根据商品关键字查询零售单,只有普通商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 零售单主表1 // 零售单商品1 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO = retailTradeCommodity1NO; // 零售单总额 final double totalRetailTradeAmount = retailTrade1Amount; // 零售总成本 final double totalpurchasingPrice = purchasingPrice1; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建一个正常状态的普通商品 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("贝贝" + Shared.generateStringByTime(4)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID() }; int[] barcodeIdArr = { barcodeCreated.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO }; double[] warehousingCommPriceArr = { warehousingCommPrice }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword(commodityGet.getName()); // 创建零售单 int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price }; int[] commIdArrForCreateRetailTrade = { commodityCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCreated.getID() }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, retailTrade1Amount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确:" + totalRetailTradeGross); } @Test public void retrieveNByCommodityNameInTimeRangeTest2() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case2:根据商品关键字查询零售单,只有多包装商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 参照商品倍数 final int refCommodityMultiple = random.nextInt(100) + 2; // 零售单主表1 // 零售单商品1 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO = retailTradeCommodity1NO; // 零售单总额 final double totalRetailTradeAmount = retailTrade1Amount; // 零售总成本 final double totalpurchasingPrice = purchasingPrice1; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建一个正常状态的普通商品 DataSourceContextHolder.setDbName(Shared.DBName_Test); Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); System.out.println(barcodeCreated); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("晶晶多包装" + Shared.generateStringByTime(4)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID() }; int[] barcodeIdArr = { barcodeCreated.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO }; double[] warehousingCommPriceArr = { warehousingCommPrice }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword(commmodityMultiPackaging.getName()); // 创建零售单 int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price }; int[] commIdArrForCreateRetailTrade = { commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeMultiPackagingCreated.getID() }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, retailTrade1Amount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest3() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case3:正常查询,根据商品关键字查询零售单,只有组合商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 "); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(100) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 零售单主表1 // 零售单商品1 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; // final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO = retailTradeCommodity1NO; // 零售单总额 final double totalRetailTradeAmount = retailTrade1Amount; // 零售总成本 final double totalpurchasingPrice = purchasingPrice1; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("组合商品" + Shared.generateStringByTime(4)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("组合"); // 创建零售单 int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price }; int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID() }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, retailTrade1Amount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确" + totalRetailTradeGross); } @Test public void retrieveNByCommodityNameInTimeRangeTest4() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case4:正常查询,根据商品关键字查询零售单,只有服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利"); // 零售单主表1 // 零售单商品1 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO = retailTradeCommodity1NO; // 零售单总额 final double totalRetailTradeAmount = retailTrade1Amount; // 零售总成本 final double totalpurchasingPrice = 0; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("迎迎" + Shared.generateStringByTime(4)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword(commodityServiceGet.getName()); // 创建零售单 int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price }; int[] commIdArrForCreateRetailTrade = { commodityServiceCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeServiceCreated.getID() }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, retailTrade1Amount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest5() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case5:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 "); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; // 零售单总额 final double totalRetailTradeAmount = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; // 零售总成本 final double totalpurchasingPrice = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; // 创建零售单 BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest6() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case6:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单)"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); System.out.println("totalpurchasingPrice1" + totalpurchasingPrice1 + "totalpurchasingPrice2" + totalpurchasingPrice2); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确" + totalRetailTradeGross); } @Test public void retrieveNByCommodityNameInTimeRangeTest7() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case7:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单)"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest8() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case8:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),商品名称不存在"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("龙行龘龘"); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() == 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount == 0, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == 0, "销售数量不正确"); Assert.assertTrue(dTotalGross == 0, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest9() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case9:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),staffID不存在"); final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setStaffID(BaseAction.INVALID_ID); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() == 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount == 0, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == 0, "销售数量不正确"); Assert.assertTrue(dTotalGross == 0, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest10() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case10:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),paymentype不存在"); final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setPaymentType(BaseAction.INVALID_ID); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() == 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount == 0, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == 0, "销售数量不正确"); Assert.assertTrue(dTotalGross == 0, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest11() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case11:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),不存在的时间段"); final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 Thread.sleep(1000); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); Thread.sleep(1000); retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() == 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount == 0, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == 0, "销售数量不正确"); Assert.assertTrue(dTotalGross == 0, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest12() throws Exception { Shared.printTestMethodStartInfo(); /* (ps:零售单售卖商品A10件、40元,售卖商品B20件、60元,那么搜索关键字商品A,结果应该是销售数量为10、销售总额为40元) */ Shared.caseLog("case12:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),有的零售商品符合传入的关键字,有的不符合关键字"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建不匹配关键字的商品 Commodity commodityGet3 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet3.setName("不匹配" + Shared.generateStringByTime(6)); Commodity commodityCreated3 = BaseCommodityTest.createCommodityViaMapper(commodityGet3, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated3 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated3); // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID(), commodityCreated3.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID(), barcodeCreated3.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID(), commodityCreated3.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID(), barcodeCreated3.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确:" + totalRetailTradeGross); } @Test public void retrieveNByCommodityNameInTimeRangeTest13() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case13:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),有的零售商品符合传入的关键字,有的不符合关键字,零售商品价格有小数"); // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建不匹配关键字的商品 Commodity commodityGet3 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet3.setName("不匹配" + Shared.generateStringByTime(6)); Commodity commodityCreated3 = BaseCommodityTest.createCommodityViaMapper(commodityGet3, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated3 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated3); // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID(), commodityCreated3.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID(), barcodeCreated3.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID(), commodityCreated3.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID(), barcodeCreated3.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest14() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case14:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),有的零售商品符合传入的关键字,有的不符合关键字,跳库,创建入库单1不审核、创建入库单2并审核"); // final int warehousingCommNO2 = random.nextInt(100) + 1; final double warehousingCommPrice2 = Math.floor((random.nextDouble() + 20) * 1000) / 1000;// 入库价2 // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + 1; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + 1; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + 1; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建不匹配关键字的商品 Commodity commodityGet3 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet3.setName("不匹配" + Shared.generateStringByTime(6)); Commodity commodityCreated3 = BaseCommodityTest.createCommodityViaMapper(commodityGet3, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated3 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated3); // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID(), commodityCreated3.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID(), barcodeCreated3.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // 入库单2,创建但不审核 // 入库商品 Warehousing warehousingGet2 = BaseWarehousingTest.DataInput.getWarehousing(); warehousingGet2.setWarehouseID(1); warehousingGet2.setStaffID(Shared.BossID); warehousingGet2.setProviderID(1); warehousingGet2.setPurchasingOrderID(purchasingOrderApproved.getID()); Warehousing warehousingCreated2 = BaseWarehousingTest.createViaMapper(warehousingGet2); // WarehousingCommodity warehousingCommodityGet23 = new WarehousingCommodity(); warehousingCommodityGet23.setCommodityID(commodityCreated3.getID()); warehousingCommodityGet23.setNO(warehousingCommNO2); warehousingCommodityGet23.setBarcodeID(barcodeCreated3.getID()); warehousingCommodityGet23.setPrice(warehousingCommPrice2); warehousingCommodityGet23.setAmount(warehousingCommPrice2 * warehousingCommNO); warehousingCommodityGet23.setShelfLife(22); warehousingCommodityGet23.setWarehousingID(warehousingCreated2.getID()); // 检查字段合法性 String errorMassage23 = warehousingCommodityGet23.checkCreate(BaseBO.INVALID_CASE_ID); Assert.assertEquals(errorMassage23, ""); // WarehousingCommodity warehousingCommCreated23 = BaseWarehousingTest.createWarehousingCommodityViaMapper(warehousingCommodityGet23); System.out.println("warehousingCommCreated23=" + warehousingCommCreated23); // WarehousingCommodity warehousingCommodityGet22 = new WarehousingCommodity(); warehousingCommodityGet22.setCommodityID(commodityCreated2.getID()); warehousingCommodityGet22.setNO(warehousingCommNO); warehousingCommodityGet22.setBarcodeID(barcodeCreated2.getID()); warehousingCommodityGet22.setPrice(warehousingCommPrice2); warehousingCommodityGet22.setAmount(warehousingCommNO * warehousingCommPrice2); warehousingCommodityGet22.setShelfLife(22); warehousingCommodityGet22.setWarehousingID(warehousingCreated2.getID()); // 检查字段合法性 String errorMassage22 = warehousingCommodityGet22.checkCreate(BaseBO.INVALID_CASE_ID); Assert.assertEquals(errorMassage22, ""); // WarehousingCommodity warehousingCommCreated22 = BaseWarehousingTest.createWarehousingCommodityViaMapper(warehousingCommodityGet22); System.out.println("warehousingCommCreated22=" + warehousingCommCreated22); WarehousingCommodity warehousingCommodityGet21 = new WarehousingCommodity(); warehousingCommodityGet21.setCommodityID(commodityCreated.getID()); warehousingCommodityGet21.setNO(warehousingCommNO); warehousingCommodityGet21.setBarcodeID(barcodeCreated.getID()); warehousingCommodityGet21.setPrice(warehousingCommPrice2); warehousingCommodityGet21.setAmount(warehousingCommNO * warehousingCommPrice2); warehousingCommodityGet21.setShelfLife(22); warehousingCommodityGet21.setWarehousingID(warehousingCreated2.getID()); // 检查字段合法性 String errorMassage21 = warehousingCommodityGet21.checkCreate(BaseBO.INVALID_CASE_ID); Assert.assertEquals(errorMassage21, ""); // WarehousingCommodity warehousingCommCreated21 = BaseWarehousingTest.createWarehousingCommodityViaMapper(warehousingCommodityGet21); System.out.println(warehousingCommCreated21); // // 创建并审核入库单 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID(), commodityCreated3.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID(), barcodeCreated3.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确"); } @Test public void retrieveNByCommodityNameInTimeRangeTest15() throws Exception { Shared.printTestMethodStartInfo(); Shared.caseLog("case15:根据商品关键字查询零售单,有普通、多包装、组合、服务商品的零售单时,是否返回正确的销售数量、销售总额、销售毛利 (2个零售单,1个退货单),有的零售商品符合传入的关键字,有的不符合关键字,跨库,入库单1售卖完、接着售卖入库单2"); final double warehousingCommPrice2 = Math.floor((random.nextDouble() + 20) * 1000) / 1000;// 入库价2 final int warehousingCommNO2 = 1;// 入库商品数量为1, 为了实现跨库,这个入库数量不随机 // 采购单主表1 // 采购商品1 final int purchasingOrderCommNO = random.nextInt(100) + 1; // 采购数量 final double priceSuggestion = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 采购价 // 入库单主表1 // 入库单从表1 final int warehousingCommNO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingCommPrice = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 final int warehousingComm2NO = random.nextInt(purchasingOrderCommNO) + 1; // 入库商品数量 final double warehousingComm2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // 入库商品价格 // 组合商品对应的子商品数量 final int subCommodity1NO = random.nextInt(100) + 1; final int subCommodity2NO = random.nextInt(100) + 1; final int refCommodityMultiple = random.nextInt(100) + 2; // 参照商品倍数 // 零售单主表2 // 零售单商品1 // 服务 final int retailTradeCommodity24NO = random.nextInt(100) + 1; final double retailTradeCommodity24Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice24 = 0; final double retailTrade24Amount = retailTradeCommodity24NO * retailTradeCommodity24Price; // 多包装,参照商品1 final int retailTradeCommodity23NO = random.nextInt(100) + 1; final double retailTradeCommodity23Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice23 = retailTradeCommodity23NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade23Amount = retailTradeCommodity23NO * retailTradeCommodity23Price; // 单品 final int retailTradeCommodity22NO = random.nextInt(100) + 1; final double retailTradeCommodity22Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice22 = retailTradeCommodity22NO * warehousingCommPrice; final double retailTrade22Amount = retailTradeCommodity22NO * retailTradeCommodity22Price; // 组合 final int retailTradeCommodity21NO = random.nextInt(100) + 1; final double retailTradeCommodity21Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice21 = retailTradeCommodity21NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity21NO * warehousingComm2Price * subCommodity2NO; final double retailTrade21Amount = retailTradeCommodity21NO * retailTradeCommodity21Price; final int totalRetailTradeCommodityNO2 = retailTradeCommodity21NO + retailTradeCommodity22NO + retailTradeCommodity23NO + retailTradeCommodity24NO; final double totalRetailTradeAmount2 = retailTrade21Amount + retailTrade22Amount + retailTrade23Amount + retailTrade24Amount; final double totalpurchasingPrice2 = purchasingPrice21 + purchasingPrice22 + purchasingPrice23 + purchasingPrice24; // 零售单主表1 // 零售单商品1 // 服务 final int retailTradeCommodity4NO = random.nextInt(100) + 1; final double retailTradeCommodity4Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice4 = 0; final double retailTrade4Amount = retailTradeCommodity4NO * retailTradeCommodity4Price; // 多包装,参照商品1 final int retailTradeCommodity3NO = random.nextInt(100) + warehousingCommNO2; final double retailTradeCommodity3Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice3 = retailTradeCommodity3NO * warehousingCommPrice * refCommodityMultiple; final double retailTrade3Amount = retailTradeCommodity3NO * retailTradeCommodity3Price; // 单品 final int retailTradeCommodity2NO = random.nextInt(100) + warehousingCommNO2; final double retailTradeCommodity2Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; final double purchasingPrice2 = retailTradeCommodity2NO * warehousingCommPrice; final double retailTrade2Amount = retailTradeCommodity2NO * retailTradeCommodity2Price; // 组合 final int retailTradeCommodity1NO = random.nextInt(100) + warehousingCommNO2; final double retailTradeCommodity1Price = Math.floor((random.nextDouble() + 20) * 1000) / 1000; // final double purchasingPrice1 = retailTradeCommodity1NO * warehousingCommPrice * subCommodity1NO + retailTradeCommodity1NO * warehousingComm2Price * subCommodity2NO; final double retailTrade1Amount = retailTradeCommodity1NO * retailTradeCommodity1Price; final int totalRetailTradeCommodityNO1 = retailTradeCommodity1NO + retailTradeCommodity2NO + retailTradeCommodity3NO + retailTradeCommodity4NO; final int totalRetailTradeCommodityNO = totalRetailTradeCommodityNO1 + totalRetailTradeCommodityNO2; // 零售单总额 final double totalRetailTradeAmount1 = retailTrade1Amount + retailTrade2Amount + retailTrade3Amount + retailTrade4Amount; final double totalRetailTradeAmount = totalRetailTradeAmount1 + totalRetailTradeAmount2; // 零售总成本 final double totalpurchasingPrice1 = purchasingPrice1 + purchasingPrice2 + purchasingPrice3 + purchasingPrice4; final double totalpurchasingPrice = totalpurchasingPrice1 + totalpurchasingPrice2 + warehousingCommPrice2 * warehousingCommNO2 * 2 - warehousingComm2Price - warehousingCommPrice; // 销售毛利 = 销售总额 - 销售成本 final double totalRetailTradeGross = totalRetailTradeAmount - totalpurchasingPrice; // 创建不匹配关键字的商品 Commodity commodityGet3 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet3.setName("不匹配" + Shared.generateStringByTime(6)); Commodity commodityCreated3 = BaseCommodityTest.createCommodityViaMapper(commodityGet3, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated3 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated3); // 创建子商品1 Commodity commodityGet = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated = BaseCommodityTest.createCommodityViaMapper(commodityGet, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated); // 创建子商品2 Commodity commodityGet2 = BaseCommodityTest.DataInput.getCommodity(CommodityType.EnumCommodityType.ECT_Normal.getIndex()); commodityGet2.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityCreated2 = BaseCommodityTest.createCommodityViaMapper(commodityGet2, BaseBO.CASE_Commodity_CreateSingle); // 创建对应的条形码 Barcodes barcodeCreated2 = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCreated2); // 创建组合商品 Commodity commodityCombinationGet = BaseCommodityTest.DataInput.getCommodity(); commodityCombinationGet.setName("多商品" + Shared.generateStringByTime(6)); commodityCombinationGet.setType(EnumCommodityType.ECT_Combination.getIndex()); Commodity commodityCombinationCreated = BaseCommodityTest.createCommodityViaMapperWithoutCreateSubCommodity(commodityCombinationGet, BaseBO.CASE_Commodity_CreateComposition); // 创建对应的条形码 Barcodes barcodeCombinationCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityCombinationCreated); // 创建从表 SubCommodity subCommodity1 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity1.setCommodityID(commodityCombinationCreated.getID()); subCommodity1.setSubCommodityID(commodityCreated.getID()); subCommodity1.setSubCommodityNO(subCommodity1NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity1); SubCommodity subCommodity2 = BaseCommodityTest.DataInput.getSubCommodity(); subCommodity2.setCommodityID(commodityCombinationCreated.getID()); subCommodity2.setSubCommodityID(commodityCreated2.getID()); subCommodity2.setSubCommodityNO(subCommodity2NO); // BaseCommodityTest.createSubCommodityViaMapper(subCommodity2); // 创建多包装 Commodity commmodityMultiPackaging = BaseCommodityTest.DataInput.getCommodity(); commmodityMultiPackaging.setName("多商品" + Shared.generateStringByTime(6)); commmodityMultiPackaging.setType(EnumCommodityType.ECT_MultiPackaging.getIndex()); commmodityMultiPackaging.setRefCommodityID(commodityCreated.getID()); commmodityMultiPackaging.setRefCommodityMultiple(refCommodityMultiple); commmodityMultiPackaging.setMultiPackagingInfo("123456789" + ";1;1;1;8;8;" + "64位条形码" + System.currentTimeMillis() % 1000000 + ";"); // 测试条形码 Commodity commmodityMultipleCreated = BaseCommodityTest.createCommodityViaMapper(commmodityMultiPackaging, BaseBO.CASE_Commodity_CreateMultiPackaging); // 创建对应的条形码 Barcodes barcodeMultiPackagingCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commmodityMultipleCreated); // 创建服务商品 Commodity commodityServiceGet = BaseCommodityTest.DataInput.getCommodity(EnumCommodityType.ECT_Service.getIndex()); commodityServiceGet.setName("多商品" + Shared.generateStringByTime(6)); Commodity commodityServiceCreated = BaseCommodityTest.createCommodityViaMapper(commodityServiceGet, BaseBO.CASE_Commodity_CreateService); // 创建对应的条形码 Barcodes barcodeServiceCreated = BaseCommodityTest.retrieveNBarcodesViaMapper(commodityServiceCreated); // 创建并审核采购订单 int[] commIdArr = { commodityCreated.getID(), commodityCreated2.getID(), commodityCreated3.getID() }; int[] barcodeIdArr = { barcodeCreated.getID(), barcodeCreated2.getID(), barcodeCreated3.getID() }; PurchasingOrder purchasingOrderApproved = BaseRetailTradeTest.createAndApprovePurchasingOrderViaMapper(purchasingOrderCommNO, priceSuggestion, commIdArr, barcodeIdArr); // // 入库单2,入库单品1、单品2、不匹配商品数量均为1,售卖完这张入库单继续售卖下一张 // // 创建并审核入库单2 int[] warehousingCommNOArr2 = { warehousingCommNO2, warehousingCommNO2, warehousingCommNO2 }; double[] warehousingCommPriceArr2 = { warehousingCommPrice2, warehousingCommPrice2, warehousingCommPrice2 }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr2, warehousingCommPriceArr2, commIdArr, barcodeIdArr, purchasingOrderApproved); // 创建并审核入库单1 int[] warehousingCommNOArr = { warehousingCommNO, warehousingComm2NO, warehousingComm2NO }; double[] warehousingCommPriceArr = { warehousingCommPrice, warehousingComm2Price, warehousingComm2Price }; BaseRetailTradeTest.createAndApproveWarehousingViaMapper(warehousingCommNOArr, warehousingCommPriceArr, commIdArr, barcodeIdArr, purchasingOrderApproved); // RetailTrade retailTradeRetrieveNCondition = new RetailTrade(); retailTradeRetrieveNCondition.setDatetimeStart(new Date()); retailTradeRetrieveNCondition.setQueryKeyword("多商品"); // 创建零售单2 int[] commIdArrForCreateRetailTrade2 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID(), commodityCreated3.getID() }; int[] barcodeIdArrForCreateRetailTrade2 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID(), barcodeCreated3.getID() }; int[] retailTradeCommodityNOArr2 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr2 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price, retailTradeCommodity23Price }; RetailTrade retailTradeCreated2 = BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr2, retailTradeCommodityPriceArr2, totalRetailTradeAmount2, commIdArrForCreateRetailTrade2, barcodeIdArrForCreateRetailTrade2, iSourceRetailTradeID); // 创建零售单1 int[] commIdArrForCreateRetailTrade = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr = { retailTradeCommodity1NO, retailTradeCommodity2NO, retailTradeCommodity4NO, retailTradeCommodity3NO }; double[] retailTradeCommodityPriceArr = { retailTradeCommodity1Price, retailTradeCommodity2Price, retailTradeCommodity4Price, retailTradeCommodity3Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr, retailTradeCommodityPriceArr, totalRetailTradeAmount, commIdArrForCreateRetailTrade, barcodeIdArrForCreateRetailTrade, iSourceRetailTradeID); // 创建零售单3 int[] commIdArrForCreateRetailTrade3 = { commodityCombinationCreated.getID(), commodityCreated.getID(), commodityServiceCreated.getID(), commmodityMultipleCreated.getID() }; int[] barcodeIdArrForCreateRetailTrade3 = { barcodeCombinationCreated.getID(), barcodeCreated.getID(), barcodeServiceCreated.getID(), barcodeMultiPackagingCreated.getID() }; int[] retailTradeCommodityNOArr3 = { retailTradeCommodity21NO, retailTradeCommodity22NO, retailTradeCommodity24NO, retailTradeCommodity23NO }; double[] retailTradeCommodityPriceArr3 = { retailTradeCommodity21Price, retailTradeCommodity22Price, retailTradeCommodity24Price, retailTradeCommodity23Price }; BaseRetailTradeTest.createRetailTradeViaMapper(retailTradeCommodityNOArr3, retailTradeCommodityPriceArr3, totalRetailTradeAmount2, commIdArrForCreateRetailTrade3, barcodeIdArrForCreateRetailTrade3, retailTradeCreated2.getID()); // 查询零售单 retailTradeRetrieveNCondition.setDatetimeEnd(new Date()); Map<String, Object> paramsForID = retailTradeRetrieveNCondition.getRetrieveNParam(BaseBO.CASE_RetailTrade_RetrieveNByCommodityNameInTimeRangeFromWeb, retailTradeRetrieveNCondition); // DataSourceContextHolder.setDbName(Shared.DBName_Test); List<BaseModel> bm = (List<BaseModel>) retailTradeMapper.retrieveNByCommodityNameInTimeRange(paramsForID); Assert.assertTrue(bm.size() != 0 && EnumErrorCode.values()[Integer.parseInt(paramsForID.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "查询对象失败"); double dRetailAmount = Double.parseDouble(paramsForID.get("dRetailAmount").toString()); int dTotalCommNO = Integer.parseInt(paramsForID.get("dTotalCommNO").toString()); double dTotalGross = Double.parseDouble(paramsForID.get("dTotalGross").toString()); System.out.println("dRetailAmount:" + dRetailAmount); System.out.println("dTotalCommNO:" + dTotalCommNO); System.out.println("dTotalGross:" + dTotalGross); Assert.assertTrue(dRetailAmount - totalRetailTradeAmount < BaseModel.TOLERANCE, "销售总额不正确"); Assert.assertTrue(dTotalCommNO == totalRetailTradeCommodityNO, "销售数量不正确"); Assert.assertTrue(dTotalGross - totalRetailTradeGross < BaseModel.TOLERANCE, "销售毛利不正确:" + totalRetailTradeGross); } }
package savickas_ignas.win10notifications; /** * Created by isavi on 2017-02-06. */ public interface Constants { // Message types sent from the BluetoothChatService Handler public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; public static final int MESSAGE_TOAST = 5; // Key names received from the BluetoothChatService Handler public static final String DEVICE_NAME = "device_name"; public static final String TOAST = "toast"; public static final String STOP_FOREGROUND_ACTION = "win10notifications.STOP_FOREGROUND"; public static final int SRV_NOTIFICATION_ID = 30000; public static final int INFO_NOTIFICATION_ID = 30001; public static final String NOTIFICATION_DELETED_ACTION = "win10notifications.NOTIFICATION_DELETED"; public static final String NOTIFICATION_LISTENER_POSTED_ACTION = "win10notifications.NOTIFICATION_LISTENER_POSTED"; public static final String NOTIFICATION_LISTENER_REMOVED_ACTION = "win10notifications.NOTIFICATION_LISTENER_REMOVED"; public static final String NOTIFICATION_LISTENER_CANCELED_ACTION = "win10notifications.NOTIFICATION_LISTENER_CANCELED"; public static final String NOTIFICATION_LISTENER_GET_ALL_ACTION = "win10notifications.NOTIFICATION_LISTENER_GET_ALL"; public static final String NOTIFICATION_LISTENER_STATE = "win10notifications.NOTIFICATION_LISTENER_STATE"; public static final String FOREGROUND_SERVICE_CHANNEL_ID = "foreground_service"; public static final String DEVICE_CONNECTION_CHANNEL_ID = "device_connection"; public static final String WINDOWS_NOTIFICATIONS_CHANNEL_ID = "windows_notifications"; public static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 10; public static final int MY_PERMISSIONS_RECEIVE_SMS = 11; public static final int MY_PERMISSIONS_INCOMING_CALL = 12; }
/* * Copyright (C) 2019 Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ package com.intel.attestationhub.plugin.nova; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import com.google.common.io.ByteStreams; public class TestUtils { public static String loadJsonData(String path) { String rawJson = ""; try (InputStream fileAsStream = TestUtils.class.getClassLoader().getResourceAsStream(path)) { if(fileAsStream == null) { fail("Unable to load Json file from path " + path); } rawJson = new String(ByteStreams.toByteArray(fileAsStream)); } catch (IOException e) { fail("Unable to load Json file from path " + path); } return rawJson; } }
class employee { String name="Saurab"; int age=23; String city="Chennai"; public void callBack() { System.out.println("The name is "+name); System.out.println("The age is "+age); System.out.println("The city name is "+city); } public static void main(String[] args) { employee c= new employee(); c.callBack(); } }
/* * Copyright 2020 ThoughtWorks, Inc. * * 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 com.thoughtworks.go.server.newsecurity.filters; import com.thoughtworks.go.ClearSingleton; import com.thoughtworks.go.config.ServerConfig; import com.thoughtworks.go.http.mocks.HttpRequestBuilder; import com.thoughtworks.go.http.mocks.MockHttpServletRequest; import com.thoughtworks.go.http.mocks.MockHttpServletResponse; import com.thoughtworks.go.http.mocks.MockHttpSession; import com.thoughtworks.go.security.Registration; import com.thoughtworks.go.security.X509CertificateGenerator; import com.thoughtworks.go.server.newsecurity.models.AgentToken; import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken; import com.thoughtworks.go.server.newsecurity.models.X509Credential; import com.thoughtworks.go.server.newsecurity.utils.SessionUtils; import com.thoughtworks.go.server.security.GoAuthority; import com.thoughtworks.go.server.security.userdetail.GoUserPrinciple; import com.thoughtworks.go.server.service.AgentService; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.util.TestingClock; import org.junit.Rule; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @EnableRuleMigrationSupport public class X509AuthenticationFilterTest { @TempDir File tempDir; private TemporaryFolder temporaryFolder; @Rule public final ClearSingleton clearSingleton = new ClearSingleton(); private final MockHttpServletResponse response = new MockHttpServletResponse(); private final FilterChain filterChain = mock(FilterChain.class); private final TestingClock clock = new TestingClock(); @BeforeEach void setUp() throws IOException { temporaryFolder = new TemporaryFolder(tempDir); temporaryFolder.create(); } @Nested class X509 { @Test void shouldPopulateAgentUserInSessionIfUse() throws Exception { final Registration registration = createRegistration("blah"); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withX509(registration.getChain()) .build(); new X509AuthenticationFilter(null, clock, null).doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication.getUser().getUsername()) .isEqualTo("_go_agent_blah"); assertThat(authentication.getUser().getAuthorities()) .hasSize(1) .contains(GoAuthority.ROLE_AGENT.asAuthority()); verify(filterChain).doFilter(request, response); assertThat(response.getStatus()).isEqualTo(200); } @Test void shouldRejectRequestWith403IfCertificateIsNotProvided() throws Exception { final MockHttpServletRequest request = HttpRequestBuilder.GET("/").build(); new X509AuthenticationFilter(null, clock, null).doFilter(request, response, filterChain); assertThat(SessionUtils.getAuthenticationToken(request)).isNull(); verifyZeroInteractions(filterChain); assertThat(response.getStatus()).isEqualTo(403); } @Test void shouldReauthenticateIfCredentialsAreProvidedInRequestEvenIfRequestWasPreviouslyAuthenticatedAsANormalUser() throws ServletException, IOException { final Registration registration = createRegistration("blah"); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withX509(registration.getChain()) .build(); com.thoughtworks.go.server.newsecurity.SessionUtilsHelper.loginAsRandomUser(request); final HttpSession originalSession = request.getSession(true); new X509AuthenticationFilter(null, clock, null).doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication.getUser().getUsername()) .isEqualTo("_go_agent_blah"); assertThat(authentication.getUser().getAuthorities()) .hasSize(1) .contains(GoAuthority.ROLE_AGENT.asAuthority()); verify(filterChain).doFilter(request, response); assertThat(response.getStatus()).isEqualTo(200); assertThat(request.getSession(false)).isNotSameAs(originalSession); } @Test void shouldReauthenticateIfCredentialsAreProvidedInRequestEvenIfRequestWasPreviouslyAuthenticatedUsingAStolenX509Certificate() throws ServletException, IOException { final Registration registration = createRegistration("good"); GoUserPrinciple goodAgentPrinciple = new GoUserPrinciple("_go_agent_good", ""); X509Credential x509Credential = new X509Credential(registration.getFirstCertificate()); MockHttpSession originalSession = new MockHttpSession(); SessionUtils.setAuthenticationTokenWithoutRecreatingSession(new AuthenticationToken<>(goodAgentPrinciple, x509Credential, null, 0, null), HttpRequestBuilder.GET("/dont-care").withSession(originalSession).build()); final Registration anotherRegistration = createRegistration("reject-me"); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withX509(anotherRegistration.getChain()) .withSession(originalSession) .build(); new X509AuthenticationFilter(null, clock, null).doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication.getUser().getUsername()) .isEqualTo("_go_agent_reject-me"); assertThat(authentication.getUser().getAuthorities()) .hasSize(1) .contains(GoAuthority.ROLE_AGENT.asAuthority()); verify(filterChain).doFilter(request, response); assertThat(response.getStatus()).isEqualTo(200); assertThat(request.getSession(false)).isNotSameAs(originalSession); } } @Nested class TokenBased { @Test void shouldPopulateAgentUserInSessionIfAgentExistsInConfig() throws Exception { GoConfigService goConfigService = mock(GoConfigService.class); AgentService agentService = mock(AgentService.class); ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureTokenGenerationKeyExists(); when(goConfigService.serverConfig()).thenReturn(serverConfig); when(agentService.isRegistered("blah")).thenReturn(true); X509AuthenticationFilter filter = new X509AuthenticationFilter(goConfigService, clock, agentService); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withHeader("X-Agent-GUID", "blah") .withHeader("Authorization", filter.hmacOf("blah")) .build(); filter.doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication.getUser().getUsername()) .isEqualTo("_go_agent_blah"); assertThat(authentication.getUser().getAuthorities()) .hasSize(1) .contains(GoAuthority.ROLE_AGENT.asAuthority()); verify(filterChain).doFilter(request, response); assertThat(response.getStatus()).isEqualTo(200); } @Test void shouldRejectRequestIfUUIDIsNotInConfig() throws Exception { GoConfigService goConfigService = mock(GoConfigService.class); AgentService agentService = mock(AgentService.class); ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureTokenGenerationKeyExists(); when(goConfigService.serverConfig()).thenReturn(serverConfig); when(agentService.isRegistered("blah")).thenReturn(false); X509AuthenticationFilter filter = new X509AuthenticationFilter(goConfigService, clock, agentService); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withHeader("X-Agent-GUID", "blah") .withHeader("Authorization", filter.hmacOf("blah")) .build(); filter.doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication).isNull(); verifyZeroInteractions(filterChain); assertThat(response.getStatus()).isEqualTo(403); } @Test void shouldRejectRequestWith403IfCredentialsAreBad() throws Exception { GoConfigService goConfigService = mock(GoConfigService.class); AgentService agentService = mock(AgentService.class); ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureTokenGenerationKeyExists(); when(goConfigService.serverConfig()).thenReturn(serverConfig); when(agentService.isRegistered("blah")).thenReturn(true); X509AuthenticationFilter filter = new X509AuthenticationFilter(goConfigService, clock, agentService); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withHeader("X-Agent-GUID", "blah") .withHeader("Authorization", "bad-authorization") .build(); filter.doFilter(request, response, filterChain); assertThat(SessionUtils.getAuthenticationToken(request)).isNull(); verifyZeroInteractions(filterChain); assertThat(response.getStatus()).isEqualTo(403); } @Test void shouldReauthenticateIfCredentialsAreProvidedInRequestEvenIfRequestWasPreviouslyAuthenticatedAsANormalUser() throws ServletException, IOException { final Registration registration = createRegistration("blah"); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withX509(registration.getChain()) .build(); com.thoughtworks.go.server.newsecurity.SessionUtilsHelper.loginAsRandomUser(request); final HttpSession originalSession = request.getSession(true); new X509AuthenticationFilter(null, clock, null).doFilter(request, response, filterChain); final AuthenticationToken authentication = SessionUtils.getAuthenticationToken(request); assertThat(authentication.getUser().getUsername()) .isEqualTo("_go_agent_blah"); assertThat(authentication.getUser().getAuthorities()) .hasSize(1) .contains(GoAuthority.ROLE_AGENT.asAuthority()); verify(filterChain).doFilter(request, response); assertThat(response.getStatus()).isEqualTo(200); assertThat(request.getSession(false)).isNotSameAs(originalSession); } @Test void shouldReAuthenticateIfSessionContainsTheSameTokenAsInRequest() throws ServletException, IOException { String uuid = "blah"; GoConfigService goConfigService = mock(GoConfigService.class); AgentService agentService = mock(AgentService.class); ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureTokenGenerationKeyExists(); when(goConfigService.serverConfig()).thenReturn(serverConfig); when(agentService.isRegistered(uuid)).thenReturn(true); X509AuthenticationFilter filter = new X509AuthenticationFilter(goConfigService, clock, agentService); MockHttpSession existingSession = new MockHttpSession(); GoUserPrinciple goodAgentPrinciple = new GoUserPrinciple("_go_agent_blah", ""); String token = filter.hmacOf(uuid); SessionUtils.setAuthenticationTokenWithoutRecreatingSession(new AuthenticationToken<>(goodAgentPrinciple, new AgentToken(uuid, token), null, 0, null), HttpRequestBuilder.GET("/dont-care").withSession(existingSession).build()); final MockHttpServletRequest request = HttpRequestBuilder.GET("/") .withHeader("X-Agent-GUID", uuid) .withHeader("Authorization", token) .withSession(existingSession) .build(); filter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(200); verify(filterChain).doFilter(any(), any()); assertThat(request.getSession(false)).isSameAs(existingSession); } } private Registration createRegistration(String hostname) throws IOException { File tempKeystoreFile = temporaryFolder.newFile(); X509CertificateGenerator certificateGenerator = new X509CertificateGenerator(); certificateGenerator.createAndStoreCACertificates(tempKeystoreFile); return certificateGenerator.createAgentCertificate(tempKeystoreFile, hostname); } }
package hitbra.hackathon.warmup.spring.repositories; import hitbra.hackathon.warmup.spring.model.Veiculo; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; public interface VeiculoRepository extends MongoRepository<Veiculo, String> { /** * Buscas Simples */ public List<Veiculo> findByMarcaLike(String marca); public List<Veiculo> findByModeloLike(String modelo); public List<Veiculo> findByAnoLike(String ano); public List<Veiculo> findByValor(Integer valor); public List<Veiculo> findByLocal(String local); public List<Veiculo> findByPlaca(String placa); public List<Veiculo> findByDataEntrada(String dataEntrada); /** * Buscas Complosta */ public List<Veiculo> findByMarcaLikeAndModeloLikeAndAnoLike(String marca,String modelo, String ano); public List<Veiculo> findByMarcaLikeAndModeloLike(String marca, String modelo); public List<Veiculo> findByMarcaLikeAndAnoLike(String marca, String ano); public List<Veiculo> findByModeloLikeAndAnoLike(String modelo,String ano); }
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.util.LuceneTestCase; public class TestPositiveScoresOnlyCollector extends LuceneTestCase { private static final class SimpleScorer extends Scorer { private int idx = -1; public SimpleScorer() { super(null); } public Explanation explain(int doc) throws IOException { return null; } public float score() throws IOException { return idx == scores.length ? Float.NaN : scores[idx]; } /** @deprecated use {@link #docID()} instead. */ public int doc() { return idx; } public int docID() { return idx; } /** @deprecated use {@link #nextDoc()} instead. */ public boolean next() throws IOException { return nextDoc() != NO_MORE_DOCS; } public int nextDoc() throws IOException { return ++idx != scores.length ? idx : NO_MORE_DOCS; } /** @deprecated use {@link #advance(int)} instead. */ public boolean skipTo(int target) throws IOException { return advance(target) != NO_MORE_DOCS; } public int advance(int target) throws IOException { idx = target; return idx < scores.length ? idx : NO_MORE_DOCS; } } // The scores must have positive as well as negative values private static final float[] scores = new float[] { 0.7767749f, -1.7839992f, 8.9925785f, 7.9608946f, -0.07948637f, 2.6356435f, 7.4950366f, 7.1490803f, -8.108544f, 4.961808f, 2.2423935f, -7.285586f, 4.6699767f }; public void testNegativeScores() throws Exception { // The Top*Collectors previously filtered out documents with <= scores. This // behavior has changed. This test checks that if PositiveOnlyScoresFilter // wraps one of these collectors, documents with <= 0 scores are indeed // filtered. int numPositiveScores = 0; for (int i = 0; i < scores.length; i++) { if (scores[i] > 0) { ++numPositiveScores; } } Scorer s = new SimpleScorer(); TopDocsCollector tdc = TopScoreDocCollector.create(scores.length, true); Collector c = new PositiveScoresOnlyCollector(tdc); c.setScorer(s); while (s.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { c.collect(0); } TopDocs td = tdc.topDocs(); ScoreDoc[] sd = td.scoreDocs; assertEquals(numPositiveScores, td.totalHits); for (int i = 0; i < sd.length; i++) { assertTrue("only positive scores should return: " + sd[i].score, sd[i].score > 0); } } }
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.dxf2.events.importer.context; import java.sql.ResultSet; import java.sql.SQLException; import org.hisp.dhis.common.IdScheme; import org.hisp.dhis.common.IdentifiableProperty; /** * @author Luciano Fiandesio */ public class IdSchemeUtils { public static String getKey( IdScheme scheme, ResultSet rs ) throws SQLException { Object id = rs.getObject( getColumnNameByScheme( scheme ) ); if ( id instanceof Long ) { return Long.toString( (Long) id ); } else if ( id instanceof Integer ) { return Integer.toString( (Integer) id ); } else { return (String) id; } } public static String getColumnNameByScheme( IdScheme idScheme ) { return getColumnNameByScheme( idScheme, null ); } public static String getColumnNameByScheme( IdScheme idScheme, String primaryKeyColumn ) { String id; if ( idScheme.is( IdentifiableProperty.ID ) ) { id = primaryKeyColumn != null ? primaryKeyColumn : "id"; } else if ( idScheme.is( IdentifiableProperty.UID ) ) { id = "uid"; } else if ( idScheme.is( IdentifiableProperty.CODE ) ) { id = "code"; } else if ( idScheme.is( IdentifiableProperty.NAME ) ) { id = "name"; } else { id = null; } return id; } }
package life.genny.qwanda.payments; import com.google.gson.annotations.Expose; public class QPaymentsUser { @Expose private String id; @Expose private QPaymentsUserInfo personalInfo; @Expose private QPaymentsUserContactInfo contactInfo; @Expose private QPaymentsLocationInfo location; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the personalInfo */ public QPaymentsUserInfo getPersonalInfo() { return personalInfo; } /** * @param personalInfo the personalInfo to set */ public void setPersonalInfo(QPaymentsUserInfo personalInfo) { this.personalInfo = personalInfo; } /** * @return the contactInfo */ public QPaymentsUserContactInfo getContactInfo() { return contactInfo; } /** * @param contactInfo the contactInfo to set */ public void setContactInfo(QPaymentsUserContactInfo contactInfo) { this.contactInfo = contactInfo; } /** * @return the location */ public QPaymentsLocationInfo getLocation() { return location; } /** * @param location the location to set */ public void setLocation(QPaymentsLocationInfo location) { this.location = location; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "QPaymentsUser [id=" + id + ", personalInfo=" + personalInfo + ", contactInfo=" + contactInfo + ", location=" + location + "]"; } /** * * @param id * @param personalInfo * @param contactInfo * @param location * This constructor is used when payments-user is created */ public QPaymentsUser(String id, QPaymentsUserInfo personalInfo, QPaymentsUserContactInfo contactInfo, QPaymentsLocationInfo location) { super(); if(id != null && !id.trim().isEmpty()) { this.id = id; } else { throw new IllegalArgumentException("Payment user ID cannot be empty"); } if(personalInfo != null) { this.personalInfo = personalInfo; } else { throw new IllegalArgumentException("Missing first name/last name/DOB in user profile"); } if(contactInfo != null) { this.contactInfo = contactInfo; } else { throw new IllegalArgumentException("Missing email ID"); } if(location != null) { this.location = location; } else { throw new IllegalArgumentException("Missing address line 1/city/state/country/postcode in address"); } } public QPaymentsUser() { super(); } /** * @param id * This constructor is used when payments-company is used */ public QPaymentsUser(String id) { super(); if(id != null && !id.trim().isEmpty()) { this.id = id; } else { throw new IllegalArgumentException("Payments user ID cannot be empty"); } } }
package edu.tamu.eider.app.model.annotation; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import edu.tamu.eider.app.model.validator.UriValidator; @Documented @Target(FIELD) @Retention(RUNTIME) @Constraint(validatedBy = UriValidator.class) public @interface ValidUri { String message() default "Inavalid URI"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr; import org.apache.commons.io.FileUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.embedded.JettyConfig; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.util.ExternalPaths; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.nio.file.Path; import java.util.Properties; import java.util.SortedMap; abstract public class SolrJettyTestBase extends SolrTestCaseJ4 { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @BeforeClass public static void beforeSolrJettyTestBase() throws Exception { } public static JettySolrRunner jetty; public static int port; public static SolrClient client = null; public static String context; public static JettySolrRunner createJetty(String solrHome, String configFile, String schemaFile, String context, boolean stopAtShutdown, SortedMap<ServletHolder,String> extraServlets) throws Exception { // creates the data dir context = context==null ? "/solr" : context; SolrJettyTestBase.context = context; JettyConfig jettyConfig = JettyConfig.builder() .setContext(context) .stopAtShutdown(stopAtShutdown) .withServlets(extraServlets) .withSSLConfig(sslConfig) .build(); Properties nodeProps = new Properties(); if (configFile != null) nodeProps.setProperty("solrconfig", configFile); if (schemaFile != null) nodeProps.setProperty("schema", schemaFile); if (System.getProperty("solr.data.dir") == null && System.getProperty("solr.hdfs.home") == null) { nodeProps.setProperty("solr.data.dir", createTempDir().toFile().getCanonicalPath()); } return createJetty(solrHome, nodeProps, jettyConfig); } public static JettySolrRunner createJetty(String solrHome, String configFile, String context) throws Exception { return createJetty(solrHome, configFile, null, context, true, null); } public static JettySolrRunner createJetty(String solrHome, JettyConfig jettyConfig) throws Exception { return createJetty(solrHome, new Properties(), jettyConfig); } public static JettySolrRunner createJetty(String solrHome) throws Exception { return createJetty(solrHome, new Properties(), JettyConfig.builder().withSSLConfig(sslConfig).build()); } public static JettySolrRunner createJetty(String solrHome, Properties nodeProperties, JettyConfig jettyConfig) throws Exception { initCore(null, null, solrHome); Path coresDir = createTempDir().resolve("cores"); Properties props = new Properties(); props.setProperty("name", DEFAULT_TEST_CORENAME); props.setProperty("configSet", "collection1"); props.setProperty("config", "${solrconfig:solrconfig.xml}"); props.setProperty("schema", "${schema:schema.xml}"); writeCoreProperties(coresDir.resolve("core"), props, "RestTestBase"); Properties nodeProps = new Properties(nodeProperties); nodeProps.setProperty("coreRootDirectory", coresDir.toString()); nodeProps.setProperty("configSetBaseDir", solrHome); ignoreException("maxWarmingSearchers"); jetty = new JettySolrRunner(solrHome, nodeProps, jettyConfig); jetty.start(); port = jetty.getLocalPort(); log.info("Jetty Assigned Port#" + port); return jetty; } @AfterClass public static void afterSolrJettyTestBase() throws Exception { if (jetty != null) { jetty.stop(); jetty = null; } if (client != null) client.close(); client = null; } public SolrClient getSolrClient() { { if (client == null) { client = createNewSolrClient(); } return client; } } /** * Create a new solr client. * If createJetty was called, an http implementation will be created, * otherwise an embedded implementation will be created. * Subclasses should override for other options. */ public SolrClient createNewSolrClient() { if (jetty != null) { try { // setup the client... String url = jetty.getBaseUrl().toString() + "/" + "collection1"; HttpSolrClient client = getHttpSolrClient(url); client.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); client.setDefaultMaxConnectionsPerHost(100); client.setMaxTotalConnections(100); return client; } catch( Exception ex ) { throw new RuntimeException( ex ); } } else { return new EmbeddedSolrServer( h.getCoreContainer(), "collection1" ); } } // Sets up the necessary config files for Jetty. At least some tests require that the solrconfig from the test // file directory are used, but some also require that the solr.xml file be explicitly there as of SOLR-4817 public static void setupJettyTestHome(File solrHome, String collection) throws Exception { copySolrHomeToTemp(solrHome, collection); } public static void cleanUpJettyHome(File solrHome) throws Exception { if (solrHome.exists()) { FileUtils.deleteDirectory(solrHome); } } public static void initCore() throws Exception { String exampleHome = legacyExampleCollection1SolrHome(); String exampleConfig = exampleHome+"/collection1/conf/solrconfig.xml"; String exampleSchema = exampleHome+"/collection1/conf/schema.xml"; initCore(exampleConfig, exampleSchema, exampleHome); } public static String legacyExampleCollection1SolrHome() { String sourceHome = ExternalPaths.SOURCE_HOME; if (sourceHome == null) throw new IllegalStateException("No source home! Cannot create the legacy example solr home directory."); String legacyExampleSolrHome = null; try { File tempSolrHome = LuceneTestCase.createTempDir().toFile(); org.apache.commons.io.FileUtils.copyFileToDirectory(new File(sourceHome, "server/solr/solr.xml"), tempSolrHome); File collection1Dir = new File(tempSolrHome, "collection1"); org.apache.commons.io.FileUtils.forceMkdir(collection1Dir); File configSetDir = new File(sourceHome, "server/solr/configsets/sample_techproducts_configs/conf"); org.apache.commons.io.FileUtils.copyDirectoryToDirectory(configSetDir, collection1Dir); Properties props = new Properties(); props.setProperty("name", "collection1"); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(FileUtils.openOutputStream(new File(collection1Dir, "core.properties")), "UTF-8"); props.store(writer, null); } finally { if (writer != null) { try { writer.close(); } catch (Exception ignore){} } } legacyExampleSolrHome = tempSolrHome.getAbsolutePath(); } catch (Exception exc) { if (exc instanceof RuntimeException) { throw (RuntimeException)exc; } else { throw new RuntimeException(exc); } } return legacyExampleSolrHome; } }
package com.engenhariasoftware.apipromocoes.services.impl; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.engenhariasoftware.apipromocoes.domain.Estado; import com.engenhariasoftware.apipromocoes.domain.dtos.EstadoDTO; import com.engenhariasoftware.apipromocoes.repositories.EstadoRepository; import com.engenhariasoftware.apipromocoes.services.EstadoService; import com.engenhariasoftware.apipromocoes.services.exceptions.DataIntegratyViolationException; import com.engenhariasoftware.apipromocoes.services.exceptions.ObjectNotFoundException; @Service public class EstadoServiceImpl implements EstadoService { @Autowired private EstadoRepository repository; @Autowired private ModelMapper mapper; @Override public Estado findById(Integer id) { Optional<Estado> obj = repository.findById(id); return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado")); } @Override public List<Estado> findAll() { return repository.findAll(); } @Override public Estado create(@Valid EstadoDTO obj) { findByNome(obj); return repository.save(mapper.map(obj, Estado.class)); } @Override public Estado update(@Valid EstadoDTO obj) { return repository.save(mapper.map(obj, Estado.class)); } @Override public void delete(Integer id) { repository.deleteById(id); } private void findByNome(EstadoDTO obj) { Optional<Estado> estado = repository.findByNome(obj.getNome()); if (estado.isPresent()) { throw new DataIntegratyViolationException("Estado já cadastrado no sistema"); } } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; public class Intake { private final LinearOpMode intake; private final DcMotor right; private final DcMotor left; private final Servo rightup; private final Servo leftup; private final Servo cap; public Intake (LinearOpMode intake){ right = intake.hardwareMap.dcMotor.get("rightintake"); left = intake.hardwareMap.dcMotor.get("leftintake"); leftup = intake.hardwareMap.servo.get("leftservo"); rightup = intake.hardwareMap.servo.get("rightservo"); cap = intake.hardwareMap.servo.get("cap"); this.intake=intake; } public void intake(double in){ right.setPower(-in); left.setPower(in); } public void lift(boolean up,boolean left, boolean right){ if(up){ rightup.setPosition(.253); leftup.setPosition(.255); } else if(left){ leftup.setPosition(0); rightup.setPosition(0); } else if(right){ rightup.setPosition(.225); leftup.setPosition(.5); } else{ rightup.setPosition(.05); leftup.setPosition(.52); } } public void capper(boolean place){ if(place){ cap.setPosition(.97); } else{ cap.setPosition(.5); } } public void telemetry(){ intake.telemetry.addData("right up position",rightup.getPosition()); intake.telemetry.addData("left up position",leftup.getPosition()); } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.mob; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtil; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.CompactionState; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Mob file cleaner chore test. * 1. Creates MOB table * 2. Load MOB data and flushes it N times * 3. Runs major MOB compaction (N MOB files go to archive) * 4. Verifies that number of MOB files in a mob directory is N+1 * 5. Waits for a period of time larger than minimum age to archive * 6. Runs Mob cleaner chore * 7 Verifies that number of MOB files in a mob directory is 1. */ @Category(MediumTests.class) public class TestMobFileCleanerChore { private static final Logger LOG = LoggerFactory.getLogger(TestMobFileCleanerChore.class); @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestMobFileCleanerChore.class); private HBaseTestingUtil HTU; private final static String famStr = "f1"; private final static byte[] fam = Bytes.toBytes(famStr); private final static byte[] qualifier = Bytes.toBytes("q1"); private final static long mobLen = 10; private final static byte[] mobVal = Bytes .toBytes("01234567890123456789012345678901234567890123456789012345678901234567890123456789"); private Configuration conf; private TableDescriptor tableDescriptor; private ColumnFamilyDescriptor familyDescriptor; private Admin admin; private Table table = null; private MobFileCleanerChore chore; private long minAgeToArchive = 10000; public TestMobFileCleanerChore() { } @Before public void setUp() throws Exception { HTU = new HBaseTestingUtil(); conf = HTU.getConfiguration(); initConf(); HTU.startMiniCluster(); admin = HTU.getAdmin(); chore = new MobFileCleanerChore(); familyDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(fam).setMobEnabled(true) .setMobThreshold(mobLen).setMaxVersions(1).build(); tableDescriptor = HTU.createModifyableTableDescriptor("testMobCompactTable") .setColumnFamily(familyDescriptor).build(); table = HTU.createTable(tableDescriptor, null); } private void initConf() { conf.setInt("hfile.format.version", 3); conf.setLong(TimeToLiveHFileCleaner.TTL_CONF_KEY, 0); conf.setInt("hbase.client.retries.number", 100); conf.setInt("hbase.hregion.max.filesize", 200000000); conf.setInt("hbase.hregion.memstore.flush.size", 800000); conf.setInt("hbase.hstore.blockingStoreFiles", 150); conf.setInt("hbase.hstore.compaction.throughput.lower.bound", 52428800); conf.setInt("hbase.hstore.compaction.throughput.higher.bound", 2 * 52428800); //conf.set(MobStoreEngine.DEFAULT_MOB_COMPACTOR_CLASS_KEY, // FaultyMobStoreCompactor.class.getName()); // Disable automatic MOB compaction conf.setLong(MobConstants.MOB_COMPACTION_CHORE_PERIOD, 0); // Disable automatic MOB file cleaner chore conf.setLong(MobConstants.MOB_CLEANER_PERIOD, 0); // Set minimum age to archive to 10 sec conf.setLong(MobConstants.MIN_AGE_TO_ARCHIVE_KEY, minAgeToArchive); // Set compacted file discharger interval to a half minAgeToArchive conf.setLong("hbase.hfile.compaction.discharger.interval", minAgeToArchive/2); } private void loadData(int start, int num) { try { for (int i = 0; i < num; i++) { Put p = new Put(Bytes.toBytes(start + i)); p.addColumn(fam, qualifier, mobVal); table.put(p); } admin.flush(table.getName()); } catch (Exception e) { LOG.error("MOB file cleaner chore test FAILED", e); assertTrue(false); } } @After public void tearDown() throws Exception { admin.disableTable(tableDescriptor.getTableName()); admin.deleteTable(tableDescriptor.getTableName()); HTU.shutdownMiniCluster(); } @Test public void testMobFileCleanerChore() throws InterruptedException, IOException { loadData(0, 10); loadData(10, 10); loadData(20, 10); long num = getNumberOfMobFiles(conf, table.getName(), new String(fam)); assertEquals(3, num); // Major compact admin.majorCompact(tableDescriptor.getTableName(), fam); // wait until compaction is complete while (admin.getCompactionState(tableDescriptor.getTableName()) != CompactionState.NONE) { Thread.sleep(100); } num = getNumberOfMobFiles(conf, table.getName(), new String(fam)); assertEquals(4, num); // We have guarantee, that compcated file discharger will run during this pause // because it has interval less than this wait time LOG.info("Waiting for {}ms", minAgeToArchive + 1000); Thread.sleep(minAgeToArchive + 1000); LOG.info("Cleaning up MOB files"); // Cleanup again chore.cleanupObsoleteMobFiles(conf, table.getName()); num = getNumberOfMobFiles(conf, table.getName(), new String(fam)); assertEquals(1, num); long scanned = scanTable(); assertEquals(30, scanned); } private long getNumberOfMobFiles(Configuration conf, TableName tableName, String family) throws IOException { FileSystem fs = FileSystem.get(conf); Path dir = MobUtils.getMobFamilyPath(conf, tableName, family); FileStatus[] stat = fs.listStatus(dir); for (FileStatus st : stat) { LOG.debug("DDDD MOB Directory content: {} size={}", st.getPath(), st.getLen()); } LOG.debug("MOB Directory content total files: {}", stat.length); return stat.length; } private long scanTable() { try { Result result; ResultScanner scanner = table.getScanner(fam); long counter = 0; while ((result = scanner.next()) != null) { assertTrue(Arrays.equals(result.getValue(fam, qualifier), mobVal)); counter++; } return counter; } catch (Exception e) { e.printStackTrace(); LOG.error("MOB file cleaner chore test FAILED"); if (HTU != null) { assertTrue(false); } else { System.exit(-1); } } return 0; } }
/** * Copyright 2011 Peter Murray-Rust et. al. * * 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.xmlcml.cml.element.main; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.xmlcml.cml.element.CMLAtom; import org.xmlcml.cml.element.CMLAtomicBasisFunction; import org.xmlcml.cml.element.CMLBasisSet.Basis; import org.xmlcml.molutil.ChemicalElement.AS; /** test CMLAtomicBasisFunction */ public class CMLAtomicBasisFunctionTest { /** * Test method for * 'org.xmlcml.cml.element.CMLAtomicBasisFunction.CMLAtomicBasisFunction(int * , int, int, String, String, String)' */ @Test public void testCMLAtomicBasisFunctionIntIntIntStringStringString() { int l = 2; int m = 1; int n = 2; String lm = "xx"; String symbol = "px"; String atomRef = "a1"; CMLAtomicBasisFunction abf = new CMLAtomicBasisFunction(l, m, n, lm, symbol, atomRef); Assert.assertEquals("l", 2, abf.getL()); Assert.assertEquals("m", 1, abf.getM()); Assert.assertEquals("n", 2, abf.getN()); Assert.assertEquals("lm", "xx", abf.getLm()); Assert.assertEquals("symbol", "px", abf.getSymbol()); Assert.assertEquals("atomRef", "a1", abf.getAtomRef()); } /** * Test method for * 'org.xmlcml.cml.element.CMLAtomicBasisFunction.getABFList(CMLAtom, * Basis)' */ @Test public void testGetABFList() { CMLAtom atom = new CMLAtom(); atom.setId("a1"); atom.setElementType(AS.H.value); List<CMLAtomicBasisFunction> abfList = CMLAtomicBasisFunction .getABFList(atom, Basis.MINIMAL); Assert.assertEquals(AS.H.value, 1, abfList.size()); Assert.assertEquals("H1", "1s(s)(null)", abfList.get(0).getString()); atom.setElementType(AS.C.value); abfList = CMLAtomicBasisFunction.getABFList(atom, Basis.MINIMAL); Assert.assertEquals(AS.C.value, 4, abfList.size()); Assert.assertEquals("C1", "2s(s)(null)", abfList.get(0).getString()); Assert.assertEquals("C2", "2px(px)(null)", abfList.get(1).getString()); Assert.assertEquals("C3", "2py(py)(null)", abfList.get(2).getString()); Assert.assertEquals("C4", "2pz(pz)(null)", abfList.get(3).getString()); atom.setElementType("Q"); abfList = CMLAtomicBasisFunction.getABFList(atom, Basis.MINIMAL); Assert.assertEquals("Q", 0, abfList.size()); } /** * run tests. * * @return the suite. * */ }
package com.wisdomguo.xifeng.modules.botset.qqgroup.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.wisdomguo.xifeng.modules.botset.qqgroup.entity.QQGroup; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface QQGroupMapper extends BaseMapper<QQGroup> { @Select("SELECT * from qqgroup") List<QQGroup> selectAll(); @Select("SELECT * from qqgroup where group_id=#{id}") QQGroup selectAllByID(String id); @Insert("insert into qqgroup value(#{id},0,0,0)") int addQQGroup(String id); @Update("update qqgroup set xf_open =#{xfopen} where group_id=#{id}") int updateOpenCloseXF(@Param("id") String id, @Param("xfopen") int xfopen); @Update("update qqgroup set dice_open =#{diceopen} where group_id=#{id}") int updateOpenCloseDice(@Param("id") String id, @Param("diceopen") int diceopen); @Update("update qqgroup set other_open =#{otheropen} where group_id=#{id}") int updateOpenCloseOther(@Param("id") String id, @Param("otheropen") int otheropen); }
// Targeted by JavaCPP version 1.5.3: DO NOT EDIT THIS FILE package org.bytedeco.flycapture.FlyCapture2_C; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import org.bytedeco.flycapture.FlyCapture2.*; import static org.bytedeco.flycapture.global.FlyCapture2.*; import static org.bytedeco.flycapture.global.FlyCapture2_C.*; /** Description of the system. */ @Properties(inherit = org.bytedeco.flycapture.presets.FlyCapture2_C.class) public class fc2SystemInfo extends Pointer { static { Loader.load(); } /** Default native constructor. */ public fc2SystemInfo() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public fc2SystemInfo(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public fc2SystemInfo(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public fc2SystemInfo position(long position) { return (fc2SystemInfo)super.position(position); } /** Operating system type as described by OSType. */ public native @Cast("fc2OSType") int osType(); public native fc2SystemInfo osType(int setter); /** Detailed description of the operating system. */ public native @Cast("char") byte osDescription(int i); public native fc2SystemInfo osDescription(int i, byte setter); @MemberGetter public native @Cast("char*") BytePointer osDescription(); /** Byte order of the system. */ public native @Cast("fc2ByteOrder") int byteOrder(); public native fc2SystemInfo byteOrder(int setter); /** Amount of memory available on the system. */ public native @Cast("size_t") long sysMemSize(); public native fc2SystemInfo sysMemSize(long setter); /** Detailed description of the CPU. */ public native @Cast("char") byte cpuDescription(int i); public native fc2SystemInfo cpuDescription(int i, byte setter); @MemberGetter public native @Cast("char*") BytePointer cpuDescription(); /** Number of cores on all CPUs on the system. */ public native @Cast("size_t") long numCpuCores(); public native fc2SystemInfo numCpuCores(long setter); /** List of drivers used. */ public native @Cast("char") byte driverList(int i); public native fc2SystemInfo driverList(int i, byte setter); @MemberGetter public native @Cast("char*") BytePointer driverList(); /** List of libraries used. */ public native @Cast("char") byte libraryList(int i); public native fc2SystemInfo libraryList(int i, byte setter); @MemberGetter public native @Cast("char*") BytePointer libraryList(); /** Detailed description of the GPU. */ public native @Cast("char") byte gpuDescription(int i); public native fc2SystemInfo gpuDescription(int i, byte setter); @MemberGetter public native @Cast("char*") BytePointer gpuDescription(); /** Screen resolution width in pixels. */ public native @Cast("size_t") long screenWidth(); public native fc2SystemInfo screenWidth(long setter); /** Screen resolution height in pixels. */ public native @Cast("size_t") long screenHeight(); public native fc2SystemInfo screenHeight(long setter); /** Reserved for future use. */ public native @Cast("unsigned int") int reserved(int i); public native fc2SystemInfo reserved(int i, int setter); @MemberGetter public native @Cast("unsigned int*") IntPointer reserved(); }
package tech.yiyehu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Import; import springfox.documentation.swagger2.annotations.EnableSwagger2; import tech.yiyehu.datasources.DynamicDataSourceConfig; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) @Import({DynamicDataSourceConfig.class}) public class AidApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(AidApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(AidApplication.class); } }
package info.smart_tools.smartactors.class_management.advanced_class_loader; import info.smart_tools.smartactors.class_management.interfaces.ismartactors_class_loader.ISmartactorsClassLoader; import org.junit.Test; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import static org.junit.Assert.*; /** * Tests for SmartactorsClassLoader */ public class SmartactorsClassLoaderTest { @Test public void checkSmartactorsClassLoaderCreation() throws Exception { ISmartactorsClassLoader ccl = SmartactorsClassLoader.newInstance("coreName", "coreVersion"); ccl.setDefault(); ISmartactorsClassLoader cl1 = SmartactorsClassLoader.newInstance("cl1", null); assertNotNull(cl1); ISmartactorsClassLoader cl2 = SmartactorsClassLoader.newInstance("cl2", null); assertNotNull(cl2); assertSame(((ClassLoader)cl2).getParent(), ClassLoader.getSystemClassLoader()); cl1.addDependency(cl2); assertNotNull(ccl.getCompilationClassLoader()); } @Test public void checkAdditionNewURL() throws Exception { URL url1 = new URL("http", "host", 9000, "filename1"); URL url2 = new URL("http", "host", 9000, "filename2"); URL url3 = new URL("http", "host", 9000, "filename1"); ISmartactorsClassLoader cl0 = SmartactorsClassLoader.newInstance("cl0", "cl0"); assertNotNull(cl0); cl0.setDefault(); ISmartactorsClassLoader cl = SmartactorsClassLoader.newInstance("clURL", "clURL"); assertNotNull(cl); cl.addDependency(cl0); cl0.addURL(url1); cl.addURL(url1); cl.addURL(url2); cl.addURL(url3); URL[] result = cl.getURLsFromDependencies(); ArrayList<URL> al = new ArrayList<URL>(); for(URL url : result) { al.add(url); } if( !al.contains(url1)) { fail(); } if( !al.contains(url2)) { fail(); } try { Class clazz = cl.loadClass("nowhere.classNotExist"); fail(); } catch (ClassNotFoundException e) { } Class clazz = cl.loadClass("java.lang.String"); } @Test public void checkGettersSetters() { ISmartactorsClassLoader cl = SmartactorsClassLoader.newInstance("cl", null); try { byte[] byteCode = { 1, 2 }; Class clazz = cl.addClass("newClass", byteCode); fail(); } catch (ClassFormatError e) { } } private void attachJarToClassLoader(String jarName, ISmartactorsClassLoader cl) throws Exception { String pathToJar = this.getClass().getClassLoader().getResource(jarName).getFile(); cl.addURL(new URL("jar:file:" + pathToJar+"!/")); } private ClassLoader createClassLoaderForJar(String jarName, ClassLoader parent) throws Exception { URLClassLoader cl; String pathToJar = this.getClass().getClassLoader().getResource(jarName).getFile(); URL url = new URL("jar:file:" + pathToJar+"!/"); URL[] urLs = {url}; cl = new URLClassLoader(urLs, parent); return cl; } private ClassLoader[] createClassLoaderSet() throws Exception { ISmartactorsClassLoader cls[] = new SmartactorsClassLoader[22]; cls[0] = SmartactorsClassLoader.newInstance("CL0", "CL0"); cls[1] = SmartactorsClassLoader.newInstance("CL1", "CL1"); cls[2] = SmartactorsClassLoader.newInstance("CL2", "CL2"); cls[3] = SmartactorsClassLoader.newInstance("CL3", "CL3"); cls[4] = SmartactorsClassLoader.newInstance("CL4", "CL4"); cls[5] = SmartactorsClassLoader.newInstance("CL5", "CL5"); cls[6] = SmartactorsClassLoader.newInstance("CL6", "CL6"); cls[7] = SmartactorsClassLoader.newInstance("CL7", "CL7"); cls[8] = SmartactorsClassLoader.newInstance("CL8", "CL8"); cls[9] = SmartactorsClassLoader.newInstance("CL9", "CL9"); cls[9].addDependency(cls[8]); cls[3].addDependency(cls[0]); cls[3].addDependency(cls[1]); cls[4].addDependency(cls[1]); cls[4].addDependency(cls[2]); cls[5].addDependency(cls[3]); cls[5].addDependency(cls[4]); cls[6].addDependency(cls[5]); cls[7].addDependency(cls[6]); attachJarToClassLoader("ifield_name.jar", (ISmartactorsClassLoader)cls[2]); attachJarToClassLoader("iobject.jar", (ISmartactorsClassLoader)cls[2]); attachJarToClassLoader("ifield.jar", (ISmartactorsClassLoader)cls[0]); attachJarToClassLoader("ifield.jar", (ISmartactorsClassLoader)cls[1]); attachJarToClassLoader("iobject-wrapper.jar", (ISmartactorsClassLoader)cls[4]); attachJarToClassLoader("ifield_name.jar", (ISmartactorsClassLoader)cls[8]); return (ClassLoader[])cls; } @Test public void performanceTestForExtendedClassLoader() throws Exception { ClassLoader[] cls; Class[] clazz = { null, null, null, null, null }; long iterations, t1, t2, t3, t4; double d, a, u, d1, d2; d = 0; a = 0; u = 0; d1 = 0.0; d2 = 0.0; iterations = 1000; for(int i=0; i<iterations+5; i++) { cls = createClassLoaderSet(); t1 = System.nanoTime(); clazz[0] = cls[9].loadClass("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"); t2 = System.nanoTime(); clazz[1] = cls[7].loadClass("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"); t3 = System.nanoTime(); if (i>4) { d += t2 - t1; a += t3 - t2; } } d /= iterations; a /= iterations; System.out.println(""); System.out.println("Average direct line class loading (ns): "+d); System.out.println("Average aroung line class loading (ns): "+a); cls = createClassLoaderSet(); ClassLoader cls8 = createClassLoaderForJar("ifield.jar", ClassLoader.getSystemClassLoader()); ClassLoader cls9 = createClassLoaderForJar("ifield_name.jar", cls8); ClassLoader cls10 = createClassLoaderForJar("iobject.jar", cls9); ClassLoader cls11 = createClassLoaderForJar("iobject-wrapper.jar", cls10); ClassLoader cls12 = new URLClassLoader(new URL[]{}, cls11); ClassLoader cls13 = new URLClassLoader(new URL[]{}, cls12); ClassLoader cls14 = new URLClassLoader(new URL[]{}, cls13); ClassLoader cls15 = new URLClassLoader(new URL[]{}, cls14); ClassLoader cls16 = new URLClassLoader(new URL[]{}, cls15); ClassLoader cls17 = new URLClassLoader(new URL[]{}, cls16); clazz[0] = cls[3].loadClass("info.smart_tools.smartactors.iobject.ifield.IField"); clazz[1] = cls[4].loadClass("info.smart_tools.smartactors.iobject.iobject.IObject"); clazz[2] = cls[4].loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); clazz[3] = cls[7].loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); clazz[4] = cls15 .loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); d = 0; a = 0; u = 0; iterations = 100000; for(int i=0; i<iterations+5; i++) { t1 = System.nanoTime(); clazz[1] = cls[4].loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); t2 = System.nanoTime(); clazz[0] = cls[7].loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); t3 = System.nanoTime(); clazz[2] = cls17 .loadClass("info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper"); t4 = System.nanoTime(); if (i>4) { d += t2 - t1; a += t3 - t2; u += t4 - t3; } } d /= iterations; a /= iterations; u /= iterations; System.out.println("Average direct line class reading (ns): "+d); System.out.println("Average around line class reading (ns): "+a); System.out.println("Average descendant line class reading (ns): "+u); } }
package com.kalai.todo; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
package com.sequenceiq.cloudbreak.blueprint.filesystem; import java.io.IOException; import java.util.Set; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.blueprint.AmbariBlueprintProcessorFactory; import com.sequenceiq.cloudbreak.blueprint.AmbariBlueprintTextProcessor; import com.sequenceiq.cloudbreak.common.json.JsonUtil; import com.sequenceiq.cloudbreak.service.CloudbreakResourceReaderService; import com.sequenceiq.cloudbreak.template.filesystem.CloudStorageConfigDetails; import com.sequenceiq.cloudbreak.template.filesystem.FileSystemConfigQueryObject; import com.sequenceiq.cloudbreak.template.filesystem.query.ConfigQueryEntries; import com.sequenceiq.cloudbreak.template.filesystem.query.ConfigQueryEntry; @Service public class AmbariCloudStorageConfigDetails { private static final Logger LOGGER = LoggerFactory.getLogger(AmbariCloudStorageConfigDetails.class); @Inject private CloudbreakResourceReaderService cloudbreakResourceReaderService; @Inject private AmbariBlueprintProcessorFactory ambariBlueprintProcessorFactory; @Inject private CloudStorageConfigDetails cloudStorageConfigDetails; private ConfigQueryEntries configQueryEntries; @PostConstruct public void init() { String configDefinitions = cloudbreakResourceReaderService.resourceDefinition("cloud-storage-location-specification"); try { configQueryEntries = JsonUtil.readValue(configDefinitions, ConfigQueryEntries.class); } catch (IOException e) { LOGGER.error("Cannot initialize configQueryEntries", e); configQueryEntries = new ConfigQueryEntries(); } } public Set<ConfigQueryEntry> queryParameters(FileSystemConfigQueryObject request) { AmbariBlueprintTextProcessor ambariBlueprintTextProcessor = ambariBlueprintProcessorFactory.get(request.getBlueprintText()); return cloudStorageConfigDetails.queryParameters(ambariBlueprintTextProcessor, configQueryEntries, request); } }
package com.oubowu.ipanda.ui; import android.annotation.SuppressLint; import android.arch.lifecycle.ViewModelProvider; import android.arch.lifecycle.ViewModelProviders; import android.databinding.DataBindingUtil; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.menu.MenuBuilder; import android.view.MenuItem; import android.view.View; import com.oubowu.ipanda.R; import com.oubowu.ipanda.base.ObserverImpl; import com.oubowu.ipanda.bean.TabIndex; import com.oubowu.ipanda.callback.OnFragmentScrollListener; import com.oubowu.ipanda.databinding.ActivityHomeBinding; import com.oubowu.ipanda.util.BarBehavior; import com.oubowu.ipanda.util.BottomNavigationViewHelper; import com.oubowu.ipanda.util.HandleBackUtil; import com.oubowu.ipanda.util.NavigationController; import com.oubowu.ipanda.util.StatusBarUtil; import com.oubowu.ipanda.util.ToastUtil; import com.oubowu.ipanda.viewmodel.HomeViewModel; import java.util.List; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; // 架构:UI负责从ViewModule取数据进行UI更新;ViewModule负责从Repository中取数据;Repository负责具体的数据业务请求,一般有网络和本地数据业务逻辑 // UI<---ViewModule<----Repository public class HomeActivity extends AppCompatActivity implements HasSupportFragmentInjector, OnFragmentScrollListener { public static final int POSITION_HOST = 0; public static final int POSITION_PANDA_LIVE = 1; public static final int POSITION_PANDA_VIDEO = 2; public static final int POSITION_PANDA_BROADCAST = 3; public static final int POSITION_CHINA_LIVE = 4; ActivityHomeBinding mHomeBinding; @Inject DispatchingAndroidInjector<Fragment> mFragmentDispatchingAndroidInjector; @Inject NavigationController mNavigationController; @Inject ViewModelProvider.Factory mFactory; private BottomNavigationView mNavigationView; private float mFirstBottomNavigationTopY = Integer.MIN_VALUE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StatusBarUtil.transparencyBar(this); if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { StatusBarUtil.setStatusBarColor(this, R.color.statusBarColorLollipop); } else { StatusBarUtil.setStatusBarColor(this, R.color.colorPrimaryDark1); StatusBarUtil.StatusBarLightMode(this, 3); } mHomeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home); initBottomNavigationView(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { if (!HandleBackUtil.handleBackPress(this)) { moveTaskToBack(true); } } @SuppressLint("RestrictedApi") private void initBottomNavigationView() { mNavigationView = mHomeBinding.bnv; BottomNavigationViewHelper.disableShiftMode(mNavigationView); HomeViewModel homeViewModel = ViewModelProviders.of(this, mFactory).get(HomeViewModel.class); homeViewModel.getTabIndex().observe(this, new ObserverImpl<List<TabIndex>>() { @Override protected void onLoading() { // Toast.makeText(HomeActivity.this, "加载中......", Toast.LENGTH_SHORT).show(); ToastUtil.showSuccessMsg("加载中......"); } @Override protected void onError(@NonNull String errorMsg) { // Toast.makeText(HomeActivity.this, "请求失败" + errorMsg, Toast.LENGTH_SHORT).show(); ToastUtil.showErrorMsg(errorMsg); } @Override protected void onSuccess(@NonNull List<TabIndex> data) { MenuBuilder menuBuilder = (MenuBuilder) mNavigationView.getMenu(); if (!data.isEmpty() && data.size() == menuBuilder.size()) { for (int i = 0; i < menuBuilder.size(); i++) { MenuItem item = menuBuilder.getItem(i); if (i == 0) { mNavigationController.navigateToHost("熊猫频道", data.get(i).url); } item.setTitle(data.get(i).title); item.setTitleCondensed(data.get(i).url); } mNavigationView.setOnNavigationItemSelectedListener(item -> { // Log.e("HomeActivity", "85行-onNavigationItemSelected(): " + item.getOrder()); String name = item.getTitle().toString(); String url = item.getTitleCondensed().toString(); switch (item.getOrder()) { case POSITION_HOST: mNavigationController.navigateToHost("熊猫频道", url); break; case POSITION_PANDA_LIVE: mNavigationController.navigateToPandaLive(name, url); break; case POSITION_PANDA_VIDEO: mNavigationController.navigateToPandaVideo(name, url); break; case POSITION_PANDA_BROADCAST: mNavigationController.navigateToPandaBroadcast(name, url); break; case POSITION_CHINA_LIVE: mNavigationController.navigateToChinaLive(name, url); break; } return true; }); mNavigationView.setOnNavigationItemReselectedListener(item -> { // 防止重复点击 }); } } }); } @Override public AndroidInjector<Fragment> supportFragmentInjector() { return mFragmentDispatchingAndroidInjector; } private BarBehavior mBarBehavior; @Override public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { if (mBarBehavior == null) { mBarBehavior = new BarBehavior(this, null); mBarBehavior.setDirection(BarBehavior.DIRECTION_REVERSE); } mBarBehavior.onNestedScroll(coordinatorLayout, mNavigationView, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); } @Override public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, float velocityX, float velocityY, boolean consumed) { if (mBarBehavior == null) { mBarBehavior = new BarBehavior(this, null); mBarBehavior.setDirection(BarBehavior.DIRECTION_REVERSE); } return mBarBehavior.onNestedFling(coordinatorLayout, mNavigationView, target, velocityX, velocityY, consumed); } // @Override // public void onNestedScrollListener(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { //// //// if (mFirstBottomNavigationTopY == Integer.MIN_VALUE) { //// mFirstBottomNavigationTopY = mNavigationView.getY(); //// } //// mNavigationView //// .setY(Math.max(Math.min(mNavigationView.getY() + dyConsumed, mFirstBottomNavigationTopY + mNavigationView.getHeight()), mFirstBottomNavigationTopY)); // // // // } }
package ru.java_testing.sandbox; /** * Created by Олеся on 20.10.2016. */ public class Distance { public static void main(String[] args) { Point p1 = new Point(1, 0); Point p2 = new Point(0, -5); //пример использования функции из запускаемого класса System.out.println("Расстояние между точками: (" + p1.x + ", " + p1.y + ") и (" + p2.x + ", " + p2.y + ") = " + distance(p1, p2)); //пример использования метода класса Point System.out.println("Расстояние между точками: (" + p1.x + ", " + p1.y + ") и (" + p2.x + ", " + p2.y + ") = " + p1.distance(p2)); } public static double distance(Point p1, Point p2) { double cathetus1 = p1.x - p2.x; //длина первого катета double cathetus2 = p1.y - p2.y; //длина второго катета return Math.sqrt(Math.pow(cathetus1, 2) + Math.pow(cathetus2, 2)); } }
package com.fishinwater.login.ui.fragment; /** * @author fishinwater-1999 * @version 2019-12-23 */ public interface ILoginView { enum ErrCode { /** * 用户名错误 */ WRONG_USER_NAME, /** * 密码错误 */ WRONG_USER_PWD, /** * 网络连接错误 */ WRONG_NET_WORK } /** * 获得用户名 * @return */ String getUserName(); /** * * 获得用户密码 * @return */ String getUserPwd(); /** * 成功回调 * @param response 要显示的信息 */ void showLoginSuccess(String response); /** * 失败回调 * @param errCode 失败原因 NAME / PASSWORD / NET */ void showLoginFailed(ErrCode errCode); }
package com.mypurecloud.sdk.v2.api.request; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.mypurecloud.sdk.v2.ApiException; import com.mypurecloud.sdk.v2.ApiClient; import com.mypurecloud.sdk.v2.ApiRequest; import com.mypurecloud.sdk.v2.ApiRequestBuilder; import com.mypurecloud.sdk.v2.ApiResponse; import com.mypurecloud.sdk.v2.Configuration; import com.mypurecloud.sdk.v2.model.*; import com.mypurecloud.sdk.v2.Pair; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import com.mypurecloud.sdk.v2.model.ErrorBody; import com.mypurecloud.sdk.v2.model.WhatsAppIntegration; import com.mypurecloud.sdk.v2.model.AnalyticsConversationWithoutAttributes; import com.mypurecloud.sdk.v2.model.AnalyticsConversationWithoutAttributesMultiGetResponse; import com.mypurecloud.sdk.v2.model.AsyncQueryStatus; import com.mypurecloud.sdk.v2.model.AnalyticsConversationAsyncQueryResponse; import com.mypurecloud.sdk.v2.model.Conversation; import com.mypurecloud.sdk.v2.model.SecureSession; import com.mypurecloud.sdk.v2.model.SecureSessionEntityListing; import com.mypurecloud.sdk.v2.model.AssignedWrapupCode; import com.mypurecloud.sdk.v2.model.WrapupCode; import com.mypurecloud.sdk.v2.model.ConversationEntityListing; import com.mypurecloud.sdk.v2.model.CallConversation; import com.mypurecloud.sdk.v2.model.CallbackConversation; import com.mypurecloud.sdk.v2.model.CallbackConversationEntityListing; import com.mypurecloud.sdk.v2.model.CallConversationEntityListing; import com.mypurecloud.sdk.v2.model.CallHistoryConversationEntityListing; import com.mypurecloud.sdk.v2.model.MaxParticipants; import com.mypurecloud.sdk.v2.model.ChatConversation; import com.mypurecloud.sdk.v2.model.WebChatMessage; import com.mypurecloud.sdk.v2.model.WebChatMessageEntityList; import com.mypurecloud.sdk.v2.model.ChatConversationEntityListing; import com.mypurecloud.sdk.v2.model.CobrowseConversation; import com.mypurecloud.sdk.v2.model.CobrowseConversationEntityListing; import com.mypurecloud.sdk.v2.model.EmailConversation; import com.mypurecloud.sdk.v2.model.EmailMessage; import com.mypurecloud.sdk.v2.model.EmailMessageListing; import com.mypurecloud.sdk.v2.model.EmailConversationEntityListing; import com.mypurecloud.sdk.v2.model.MessageConversation; import com.mypurecloud.sdk.v2.model.MessageMediaData; import com.mypurecloud.sdk.v2.model.MessageData; import com.mypurecloud.sdk.v2.model.MessageConversationEntityListing; import com.mypurecloud.sdk.v2.model.MessagingIntegrationEntityListing; import com.mypurecloud.sdk.v2.model.FacebookIntegrationEntityListing; import com.mypurecloud.sdk.v2.model.FacebookIntegration; import com.mypurecloud.sdk.v2.model.LineIntegrationEntityListing; import com.mypurecloud.sdk.v2.model.LineIntegration; import com.mypurecloud.sdk.v2.model.TwitterIntegrationEntityListing; import com.mypurecloud.sdk.v2.model.TwitterIntegration; import com.mypurecloud.sdk.v2.model.WhatsAppIntegrationEntityListing; import com.mypurecloud.sdk.v2.model.MessagingStickerEntityListing; import com.mypurecloud.sdk.v2.model.MediaParticipantRequest; import com.mypurecloud.sdk.v2.model.ParticipantAttributes; import com.mypurecloud.sdk.v2.model.Empty; import com.mypurecloud.sdk.v2.model.ConsultTransferUpdate; import com.mypurecloud.sdk.v2.model.ConsultTransferResponse; import com.mypurecloud.sdk.v2.model.WhatsAppIntegrationUpdateRequest; import com.mypurecloud.sdk.v2.model.PropertyIndexRequest; import com.mypurecloud.sdk.v2.model.ConversationAggregateQueryResponse; import com.mypurecloud.sdk.v2.model.ConversationAggregationQuery; import com.mypurecloud.sdk.v2.model.AsyncConversationQuery; import com.mypurecloud.sdk.v2.model.AsyncQueryResponse; import com.mypurecloud.sdk.v2.model.AnalyticsConversationQueryResponse; import com.mypurecloud.sdk.v2.model.ConversationQuery; import com.mypurecloud.sdk.v2.model.CreateCallbackOnConversationCommand; import com.mypurecloud.sdk.v2.model.Digits; import com.mypurecloud.sdk.v2.model.TransferRequest; import com.mypurecloud.sdk.v2.model.CreateSecureSession; import com.mypurecloud.sdk.v2.model.CallCommand; import com.mypurecloud.sdk.v2.model.ConsultTransfer; import com.mypurecloud.sdk.v2.model.CreateCallbackResponse; import com.mypurecloud.sdk.v2.model.CreateCallbackCommand; import com.mypurecloud.sdk.v2.model.CreateCallRequest; import com.mypurecloud.sdk.v2.model.CreateCallResponse; import com.mypurecloud.sdk.v2.model.CreateWebChatMessageRequest; import com.mypurecloud.sdk.v2.model.WebChatTyping; import com.mypurecloud.sdk.v2.model.CreateWebChatRequest; import com.mypurecloud.sdk.v2.model.InboundMessageRequest; import com.mypurecloud.sdk.v2.model.CreateEmailRequest; import com.mypurecloud.sdk.v2.model.FaxSendResponse; import com.mypurecloud.sdk.v2.model.FaxSendRequest; import com.mypurecloud.sdk.v2.model.AdditionalMessage; import com.mypurecloud.sdk.v2.model.TextMessageListing; import com.mypurecloud.sdk.v2.model.CreateOutboundMessagingConversationRequest; import com.mypurecloud.sdk.v2.model.SendAgentlessOutboundMessageRequest; import com.mypurecloud.sdk.v2.model.SendAgentlessOutboundMessageResponse; import com.mypurecloud.sdk.v2.model.FacebookIntegrationRequest; import com.mypurecloud.sdk.v2.model.LineIntegrationRequest; import com.mypurecloud.sdk.v2.model.TwitterIntegrationRequest; import com.mypurecloud.sdk.v2.model.WhatsAppIntegrationRequest; import com.mypurecloud.sdk.v2.model.SetUuiDataRequest; public class PostAnalyticsConversationsAggregatesQueryRequest { private ConversationAggregationQuery body; public ConversationAggregationQuery getBody() { return this.body; } public void setBody(ConversationAggregationQuery body) { this.body = body; } public PostAnalyticsConversationsAggregatesQueryRequest withBody(ConversationAggregationQuery body) { this.setBody(body); return this; } private final Map<String, String> customHeaders = new HashMap<>(); public Map<String, String> getCustomHeaders() { return this.customHeaders; } public void setCustomHeaders(Map<String, String> customHeaders) { this.customHeaders.clear(); this.customHeaders.putAll(customHeaders); } public void addCustomHeader(String name, String value) { this.customHeaders.put(name, value); } public PostAnalyticsConversationsAggregatesQueryRequest withCustomHeader(String name, String value) { this.addCustomHeader(name, value); return this; } public ApiRequest<ConversationAggregationQuery> withHttpInfo() { // verify the required parameter 'body' is set if (this.body == null) { throw new IllegalStateException("Missing the required parameter 'body' when building request for PostAnalyticsConversationsAggregatesQueryRequest."); } return ApiRequestBuilder.create("POST", "/api/v2/analytics/conversations/aggregates/query") .withBody(body) .withCustomHeaders(customHeaders) .withContentTypes("application/json") .withAccepts("application/json") .withAuthNames("PureCloud OAuth") .build(); } public static Builder builder() { return new Builder(); } public static Builder builder(ConversationAggregationQuery body) { return new Builder() .withRequiredParams(body); } public static class Builder { private final PostAnalyticsConversationsAggregatesQueryRequest request; private Builder() { request = new PostAnalyticsConversationsAggregatesQueryRequest(); } public Builder withBody(ConversationAggregationQuery body) { request.setBody(body); return this; } public Builder withRequiredParams(ConversationAggregationQuery body) { request.setBody(body); return this; } public PostAnalyticsConversationsAggregatesQueryRequest build() { // verify the required parameter 'body' is set if (request.body == null) { throw new IllegalStateException("Missing the required parameter 'body' when building request for PostAnalyticsConversationsAggregatesQueryRequest."); } return request; } } }
package computepoly; import java.math.BigInteger; import java.util.Objects; public class Index { private BigInteger powx; private BigInteger cos; private BigInteger sin; Index() { this.powx = BigInteger.ZERO; this.cos = BigInteger.ZERO; this.sin = BigInteger.ZERO; } Index(BigInteger powx, BigInteger cos, BigInteger sin) { this.powx = powx; this.cos = cos; this.sin = sin; } /* public boolean isCons() { return powx.equals(BigInteger.ZERO) & cos.equals(BigInteger.ZERO) & sin.equals(BigInteger.ZERO); } public void setPowx(BigInteger powx) { this.powx = powx; } public void setCos(BigInteger cos) { this.cos = cos; } public void setSin(BigInteger sin) { this.sin = sin; } */ BigInteger getPowx() { return powx; } BigInteger getCos() { return cos; } BigInteger getSin() { return sin; } void addX(BigInteger x) { this.powx = this.powx.add(x); } void addCos(BigInteger cos) { this.cos = this.cos.add(cos); } void addSin(BigInteger sin) { this.sin = this.sin.add(sin); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Index index = (Index) o; return Objects.equals(powx, index.powx) && Objects.equals(cos, index.cos) && Objects.equals(sin, index.sin); } @Override public int hashCode() { return Objects.hash(powx, cos, sin); } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block; import alluxio.Configuration; import alluxio.ProcessUtils; import alluxio.PropertyKey; import alluxio.StorageTierAssoc; import alluxio.WorkerStorageTierAssoc; import alluxio.exception.ConnectionFailedException; import alluxio.heartbeat.HeartbeatExecutor; import alluxio.metrics.Metric; import alluxio.metrics.MetricsSystem; import alluxio.thrift.Command; import alluxio.util.ConfigurationUtils; import alluxio.wire.ConfigProperty; import alluxio.wire.Scope; import alluxio.wire.WorkerNetAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.concurrent.NotThreadSafe; /** * Task that carries out the necessary block worker to master communications, including register and * heartbeat. This class manages its own {@link BlockMasterClient}. * * When running, this task first requests a block report from the * {@link alluxio.worker.block.BlockWorker}, then sends it to the master. The master may * respond to the heartbeat with a command which will be executed. After which, the task will wait * for the elapsed time since its last heartbeat has reached the heartbeat interval. Then the cycle * will continue. * * If the task fails to heartbeat to the master, it will destroy its old master client and recreate * it before retrying. */ @NotThreadSafe public final class BlockMasterSync implements HeartbeatExecutor { private static final Logger LOG = LoggerFactory.getLogger(BlockMasterSync.class); /** The block worker responsible for interacting with Alluxio and UFS storage. */ private final BlockWorker mBlockWorker; /** The worker ID for the worker. This may change if the master asks the worker to re-register. */ private final AtomicReference<Long> mWorkerId; /** The net address of the worker. */ private final WorkerNetAddress mWorkerAddress; /** Milliseconds between heartbeats before a timeout. */ private final int mHeartbeatTimeoutMs; /** Client for all master communication. */ private final BlockMasterClient mMasterClient; /** An async service to remove block. */ private final AsyncBlockRemover mAsyncBlockRemover; /** Last System.currentTimeMillis() timestamp when a heartbeat successfully completed. */ private long mLastSuccessfulHeartbeatMs; /** * Creates a new instance of {@link BlockMasterSync}. * * @param blockWorker the {@link BlockWorker} this syncer is updating to * @param workerId the worker id of the worker, assigned by the block master * @param workerAddress the net address of the worker * @param masterClient the Alluxio master client */ BlockMasterSync(BlockWorker blockWorker, AtomicReference<Long> workerId, WorkerNetAddress workerAddress, BlockMasterClient masterClient) throws IOException { mBlockWorker = blockWorker; mWorkerId = workerId; mWorkerAddress = workerAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_TIMEOUT_MS); mAsyncBlockRemover = new AsyncBlockRemover(mBlockWorker); registerWithMaster(); mLastSuccessfulHeartbeatMs = System.currentTimeMillis(); } /** * Registers with the Alluxio master. This should be called before the continuous heartbeat thread * begins. */ private void registerWithMaster() throws IOException { BlockStoreMeta storeMeta = mBlockWorker.getStoreMetaFull(); StorageTierAssoc storageTierAssoc = new WorkerStorageTierAssoc(); List<ConfigProperty> configList = ConfigurationUtils.getConfiguration(Scope.WORKER); mMasterClient.register(mWorkerId.get(), storageTierAssoc.getOrderedStorageAliases(), storeMeta.getCapacityBytesOnTiers(), storeMeta.getUsedBytesOnTiers(), storeMeta.getBlockList(), configList); } /** * Heartbeats to the master node about the change in the worker's managed space. */ @Override public void heartbeat() { // Prepare metadata for the next heartbeat BlockHeartbeatReport blockReport = mBlockWorker.getReport(); BlockStoreMeta storeMeta = mBlockWorker.getStoreMeta(); // Send the heartbeat and execute the response Command cmdFromMaster = null; List<alluxio.thrift.Metric> metrics = new ArrayList<>(); for (Metric metric : MetricsSystem.allWorkerMetrics()) { metrics.add(metric.toThrift()); } try { cmdFromMaster = mMasterClient.heartbeat(mWorkerId.get(), storeMeta.getUsedBytesOnTiers(), blockReport.getRemovedBlocks(), blockReport.getAddedBlocks(), metrics); handleMasterCommand(cmdFromMaster); mLastSuccessfulHeartbeatMs = System.currentTimeMillis(); } catch (IOException | ConnectionFailedException e) { // An error occurred, log and ignore it or error if heartbeat timeout is reached if (cmdFromMaster == null) { LOG.error("Failed to receive master heartbeat command.", e); } else { LOG.error("Failed to receive or execute master heartbeat command: {}", cmdFromMaster.toString(), e); } mMasterClient.disconnect(); if (mHeartbeatTimeoutMs > 0) { if (System.currentTimeMillis() - mLastSuccessfulHeartbeatMs >= mHeartbeatTimeoutMs) { if (Configuration.getBoolean(PropertyKey.TEST_MODE)) { throw new RuntimeException("Master heartbeat timeout exceeded: " + mHeartbeatTimeoutMs); } // TODO(andrew): Propagate the exception to the main thread and exit there. ProcessUtils.fatalError(LOG, "Master heartbeat timeout exceeded: %d", mHeartbeatTimeoutMs); } } } } @Override public void close() { mAsyncBlockRemover.shutDown(); } /** * Handles a master command. The command is one of Unknown, Nothing, Register, Free, or Delete. * This call will block until the command is complete. * * @param cmd the command to execute * @throws IOException if I/O errors occur * @throws ConnectionFailedException if connection fails */ // TODO(calvin): Evaluate the necessity of each command. private void handleMasterCommand(Command cmd) throws IOException, ConnectionFailedException { if (cmd == null) { return; } switch (cmd.getCommandType()) { // Currently unused case Delete: break; // Master requests blocks to be removed from Alluxio managed space. case Free: mAsyncBlockRemover.addBlocksToDelete(cmd.getData()); break; // No action required case Nothing: break; // Master requests re-registration case Register: mWorkerId.set(mMasterClient.getId(mWorkerAddress)); registerWithMaster(); break; // Unknown request case Unknown: LOG.error("Master heartbeat sends unknown command {}", cmd); break; default: throw new RuntimeException("Un-recognized command from master " + cmd); } } }
/*_############################################################################ _## _## SNMP4J 2 - UsmUserEvent.java _## _## Copyright (C) 2003-2013 Frank Fock and Jochen Katz (SNMP4J.org) _## _## Licensed under the Apache License, Version 2.0 (the "License"); _## you may not use this file except in compliance with the License. _## You may obtain a copy of the License at _## _## http://www.apache.org/licenses/LICENSE-2.0 _## _## Unless required by applicable law or agreed to in writing, software _## distributed under the License is distributed on an "AS IS" BASIS, _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. _## See the License for the specific language governing permissions and _## limitations under the License. _## _##########################################################################*/ package org.snmp4j.event; import java.util.EventObject; import org.snmp4j.security.SecurityModel; import org.snmp4j.security.UsmUserEntry; // needed for JavaDoc import org.snmp4j.security.USM; import org.snmp4j.security.UsmUserTable; /** * This Event is issued whenever a user of the {@link USM} is created * modified or deleted. * * @author Frank Fock * @version 1.0 */ public class UsmUserEvent extends EventObject { private static final long serialVersionUID = -2650579887988635391L; /** * Constant: a new user was created. */ public static final int USER_ADDED = 1; /** * Constant: a user was deleted. */ public static final int USER_REMOVED = 2; /** * Constant: a user was changed (but not deleted). */ public static final int USER_CHANGED = 3; private org.snmp4j.security.UsmUserEntry user; private int type; /** * Construct a UsmUserEvent. * * @param source * the object that emitts this event * @param changedEntry * the changed entry * @param type * can be USER_ADDED, USER_REMOVED or USER_CHANGED. */ public UsmUserEvent(SecurityModel source, UsmUserEntry changedEntry, int type) { super(source); this.user = changedEntry; this.type = type; } /** * Get the modified entry of the {@link UsmUserTable}. * * @return the entry <ul> * <li> after the modification if the user was added or modified * <li> before the modification if the user was deleted </ul> */ public org.snmp4j.security.UsmUserEntry getUser() { return user; } /** * Return the type of operation that triggered this event. * * @return One of USER_ADDED, USER_REMOVED or USER_CHANGED. */ public int getType() { return type; } }
/* * Copyright 2016 - 2017, Acciente LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hr.framework.config.security.oacc.conf.starter.resources.exceptions; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import io.dropwizard.jersey.errors.ErrorMessage; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> { private final Meter exceptions; public IllegalArgumentExceptionMapper(MetricRegistry metrics) { exceptions = metrics.meter(getClass().getCanonicalName() + " exceptions"); } @Override public Response toResponse(IllegalArgumentException e) { exceptions.mark(); if (e.getMessage().matches("Resource .* not found!")) { return Response .status(Response.Status.NOT_FOUND) // 404 .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorMessage(Response.Status.UNAUTHORIZED.getStatusCode(), e.getMessage())) .build(); } return Response .status(422) // UNPROCESSABLE_ENTITY .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorMessage(422, e.getMessage())) .build(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2/fulfillment.proto package com.google.cloud.dialogflow.v2; /** * <pre> * By default, your agent responds to a matched intent with a static response. * As an alternative, you can provide a more dynamic response by using * fulfillment. When you enable fulfillment for an intent, Dialogflow responds * to that intent by calling a service that you define. For example, if an * end-user wants to schedule a haircut on Friday, your service can check your * database and respond to the end-user with availability information for * Friday. * For more information, see the [fulfillment * guide](https://cloud.google.com/dialogflow/docs/fulfillment-overview). * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment} */ public final class Fulfillment extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.Fulfillment) FulfillmentOrBuilder { private static final long serialVersionUID = 0L; // Use Fulfillment.newBuilder() to construct. private Fulfillment(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Fulfillment() { name_ = ""; displayName_ = ""; features_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Fulfillment(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Fulfillment( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); displayName_ = s; break; } case 26: { com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder subBuilder = null; if (fulfillmentCase_ == 3) { subBuilder = ((com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_).toBuilder(); } fulfillment_ = input.readMessage(com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_); fulfillment_ = subBuilder.buildPartial(); } fulfillmentCase_ = 3; break; } case 32: { enabled_ = input.readBool(); break; } case 42: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { features_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2.Fulfillment.Feature>(); mutable_bitField0_ |= 0x00000001; } features_.add( input.readMessage(com.google.cloud.dialogflow.v2.Fulfillment.Feature.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { features_ = java.util.Collections.unmodifiableList(features_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.class, com.google.cloud.dialogflow.v2.Fulfillment.Builder.class); } public interface GenericWebServiceOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2.Fulfillment.GenericWebService) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The uri. */ java.lang.String getUri(); /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for uri. */ com.google.protobuf.ByteString getUriBytes(); /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The username. */ java.lang.String getUsername(); /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for username. */ com.google.protobuf.ByteString getUsernameBytes(); /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The password. */ java.lang.String getPassword(); /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ int getRequestHeadersCount(); /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ boolean containsRequestHeaders( java.lang.String key); /** * Use {@link #getRequestHeadersMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getRequestHeaders(); /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.util.Map<java.lang.String, java.lang.String> getRequestHeadersMap(); /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.lang.String getRequestHeadersOrDefault( java.lang.String key, java.lang.String defaultValue); /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.lang.String getRequestHeadersOrThrow( java.lang.String key); /** * <pre> * Optional. Indicates if generic web service is created through Cloud Functions * integration. Defaults to false. * is_cloud_function is deprecated. Cloud functions can be configured by * its uri as a regular web service now. * </pre> * * <code>bool is_cloud_function = 5 [deprecated = true, (.google.api.field_behavior) = OPTIONAL];</code> * @return The isCloudFunction. */ @java.lang.Deprecated boolean getIsCloudFunction(); } /** * <pre> * Represents configuration for a generic web service. * Dialogflow supports two mechanisms for authentications: * - Basic authentication with username and password. * - Authentication with additional authentication headers. * More information could be found at: * https://cloud.google.com/dialogflow/docs/fulfillment-configure. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment.GenericWebService} */ public static final class GenericWebService extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.Fulfillment.GenericWebService) GenericWebServiceOrBuilder { private static final long serialVersionUID = 0L; // Use GenericWebService.newBuilder() to construct. private GenericWebService(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GenericWebService() { uri_ = ""; username_ = ""; password_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new GenericWebService(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private GenericWebService( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); uri_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); username_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); password_ = s; break; } case 34: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { requestHeaders_ = com.google.protobuf.MapField.newMapField( RequestHeadersDefaultEntryHolder.defaultEntry); mutable_bitField0_ |= 0x00000001; } com.google.protobuf.MapEntry<java.lang.String, java.lang.String> requestHeaders__ = input.readMessage( RequestHeadersDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); requestHeaders_.getMutableMap().put( requestHeaders__.getKey(), requestHeaders__.getValue()); break; } case 40: { isCloudFunction_ = input.readBool(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapField internalGetMapField( int number) { switch (number) { case 4: return internalGetRequestHeaders(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.class, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder.class); } public static final int URI_FIELD_NUMBER = 1; private volatile java.lang.Object uri_; /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The uri. */ @java.lang.Override public java.lang.String getUri() { java.lang.Object ref = uri_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uri_ = s; return s; } } /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for uri. */ @java.lang.Override public com.google.protobuf.ByteString getUriBytes() { java.lang.Object ref = uri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int USERNAME_FIELD_NUMBER = 2; private volatile java.lang.Object username_; /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The username. */ @java.lang.Override public java.lang.String getUsername() { java.lang.Object ref = username_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); username_ = s; return s; } } /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for username. */ @java.lang.Override public com.google.protobuf.ByteString getUsernameBytes() { java.lang.Object ref = username_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); username_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 3; private volatile java.lang.Object password_; /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_HEADERS_FIELD_NUMBER = 4; private static final class RequestHeadersDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry .<java.lang.String, java.lang.String>newDefaultInstance( com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_RequestHeadersEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } private com.google.protobuf.MapField< java.lang.String, java.lang.String> requestHeaders_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetRequestHeaders() { if (requestHeaders_ == null) { return com.google.protobuf.MapField.emptyMapField( RequestHeadersDefaultEntryHolder.defaultEntry); } return requestHeaders_; } public int getRequestHeadersCount() { return internalGetRequestHeaders().getMap().size(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsRequestHeaders( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetRequestHeaders().getMap().containsKey(key); } /** * Use {@link #getRequestHeadersMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getRequestHeaders() { return getRequestHeadersMap(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getRequestHeadersMap() { return internalGetRequestHeaders().getMap(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getRequestHeadersOrDefault( java.lang.String key, java.lang.String defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, java.lang.String> map = internalGetRequestHeaders().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getRequestHeadersOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, java.lang.String> map = internalGetRequestHeaders().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public static final int IS_CLOUD_FUNCTION_FIELD_NUMBER = 5; private boolean isCloudFunction_; /** * <pre> * Optional. Indicates if generic web service is created through Cloud Functions * integration. Defaults to false. * is_cloud_function is deprecated. Cloud functions can be configured by * its uri as a regular web service now. * </pre> * * <code>bool is_cloud_function = 5 [deprecated = true, (.google.api.field_behavior) = OPTIONAL];</code> * @return The isCloudFunction. */ @java.lang.Override @java.lang.Deprecated public boolean getIsCloudFunction() { return isCloudFunction_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, uri_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(username_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, username_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, password_); } com.google.protobuf.GeneratedMessageV3 .serializeStringMapTo( output, internalGetRequestHeaders(), RequestHeadersDefaultEntryHolder.defaultEntry, 4); if (isCloudFunction_ != false) { output.writeBool(5, isCloudFunction_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, uri_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(username_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, username_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, password_); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetRequestHeaders().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> requestHeaders__ = RequestHeadersDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, requestHeaders__); } if (isCloudFunction_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, isCloudFunction_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService other = (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) obj; if (!getUri() .equals(other.getUri())) return false; if (!getUsername() .equals(other.getUsername())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!internalGetRequestHeaders().equals( other.internalGetRequestHeaders())) return false; if (getIsCloudFunction() != other.getIsCloudFunction()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + URI_FIELD_NUMBER; hash = (53 * hash) + getUri().hashCode(); hash = (37 * hash) + USERNAME_FIELD_NUMBER; hash = (53 * hash) + getUsername().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); if (!internalGetRequestHeaders().getMap().isEmpty()) { hash = (37 * hash) + REQUEST_HEADERS_FIELD_NUMBER; hash = (53 * hash) + internalGetRequestHeaders().hashCode(); } hash = (37 * hash) + IS_CLOUD_FUNCTION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsCloudFunction()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Represents configuration for a generic web service. * Dialogflow supports two mechanisms for authentications: * - Basic authentication with username and password. * - Authentication with additional authentication headers. * More information could be found at: * https://cloud.google.com/dialogflow/docs/fulfillment-configure. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment.GenericWebService} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.Fulfillment.GenericWebService) com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField( int number) { switch (number) { case 4: return internalGetRequestHeaders(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMutableMapField( int number) { switch (number) { case 4: return internalGetMutableRequestHeaders(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.class, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); uri_ = ""; username_ = ""; password_ = ""; internalGetMutableRequestHeaders().clear(); isCloudFunction_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_GenericWebService_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService build() { com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService buildPartial() { com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService result = new com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService(this); int from_bitField0_ = bitField0_; result.uri_ = uri_; result.username_ = username_; result.password_ = password_; result.requestHeaders_ = internalGetRequestHeaders(); result.requestHeaders_.makeImmutable(); result.isCloudFunction_ = isCloudFunction_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) { return mergeFrom((com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService other) { if (other == com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance()) return this; if (!other.getUri().isEmpty()) { uri_ = other.uri_; onChanged(); } if (!other.getUsername().isEmpty()) { username_ = other.username_; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; onChanged(); } internalGetMutableRequestHeaders().mergeFrom( other.internalGetRequestHeaders()); if (other.getIsCloudFunction() != false) { setIsCloudFunction(other.getIsCloudFunction()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object uri_ = ""; /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The uri. */ public java.lang.String getUri() { java.lang.Object ref = uri_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uri_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for uri. */ public com.google.protobuf.ByteString getUriBytes() { java.lang.Object ref = uri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The uri to set. * @return This builder for chaining. */ public Builder setUri( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uri_ = value; onChanged(); return this; } /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearUri() { uri_ = getDefaultInstance().getUri(); onChanged(); return this; } /** * <pre> * Required. The fulfillment URI for receiving POST requests. * It must use https protocol. * </pre> * * <code>string uri = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for uri to set. * @return This builder for chaining. */ public Builder setUriBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uri_ = value; onChanged(); return this; } private java.lang.Object username_ = ""; /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The username. */ public java.lang.String getUsername() { java.lang.Object ref = username_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); username_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for username. */ public com.google.protobuf.ByteString getUsernameBytes() { java.lang.Object ref = username_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); username_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The username to set. * @return This builder for chaining. */ public Builder setUsername( java.lang.String value) { if (value == null) { throw new NullPointerException(); } username_ = value; onChanged(); return this; } /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearUsername() { username_ = getDefaultInstance().getUsername(); onChanged(); return this; } /** * <pre> * Optional. The user name for HTTP Basic authentication. * </pre> * * <code>string username = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The bytes for username to set. * @return This builder for chaining. */ public Builder setUsernameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); username_ = value; onChanged(); return this; } private java.lang.Object password_ = ""; /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; onChanged(); return this; } /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); onChanged(); return this; } /** * <pre> * Optional. The password for HTTP Basic authentication. * </pre> * * <code>string password = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; onChanged(); return this; } private com.google.protobuf.MapField< java.lang.String, java.lang.String> requestHeaders_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetRequestHeaders() { if (requestHeaders_ == null) { return com.google.protobuf.MapField.emptyMapField( RequestHeadersDefaultEntryHolder.defaultEntry); } return requestHeaders_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableRequestHeaders() { onChanged();; if (requestHeaders_ == null) { requestHeaders_ = com.google.protobuf.MapField.newMapField( RequestHeadersDefaultEntryHolder.defaultEntry); } if (!requestHeaders_.isMutable()) { requestHeaders_ = requestHeaders_.copy(); } return requestHeaders_; } public int getRequestHeadersCount() { return internalGetRequestHeaders().getMap().size(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsRequestHeaders( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetRequestHeaders().getMap().containsKey(key); } /** * Use {@link #getRequestHeadersMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getRequestHeaders() { return getRequestHeadersMap(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getRequestHeadersMap() { return internalGetRequestHeaders().getMap(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getRequestHeadersOrDefault( java.lang.String key, java.lang.String defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, java.lang.String> map = internalGetRequestHeaders().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getRequestHeadersOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, java.lang.String> map = internalGetRequestHeaders().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearRequestHeaders() { internalGetMutableRequestHeaders().getMutableMap() .clear(); return this; } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder removeRequestHeaders( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } internalGetMutableRequestHeaders().getMutableMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableRequestHeaders() { return internalGetMutableRequestHeaders().getMutableMap(); } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putRequestHeaders( java.lang.String key, java.lang.String value) { if (key == null) { throw new java.lang.NullPointerException(); } if (value == null) { throw new java.lang.NullPointerException(); } internalGetMutableRequestHeaders().getMutableMap() .put(key, value); return this; } /** * <pre> * Optional. The HTTP request headers to send together with fulfillment requests. * </pre> * * <code>map&lt;string, string&gt; request_headers = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putAllRequestHeaders( java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableRequestHeaders().getMutableMap() .putAll(values); return this; } private boolean isCloudFunction_ ; /** * <pre> * Optional. Indicates if generic web service is created through Cloud Functions * integration. Defaults to false. * is_cloud_function is deprecated. Cloud functions can be configured by * its uri as a regular web service now. * </pre> * * <code>bool is_cloud_function = 5 [deprecated = true, (.google.api.field_behavior) = OPTIONAL];</code> * @return The isCloudFunction. */ @java.lang.Override @java.lang.Deprecated public boolean getIsCloudFunction() { return isCloudFunction_; } /** * <pre> * Optional. Indicates if generic web service is created through Cloud Functions * integration. Defaults to false. * is_cloud_function is deprecated. Cloud functions can be configured by * its uri as a regular web service now. * </pre> * * <code>bool is_cloud_function = 5 [deprecated = true, (.google.api.field_behavior) = OPTIONAL];</code> * @param value The isCloudFunction to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setIsCloudFunction(boolean value) { isCloudFunction_ = value; onChanged(); return this; } /** * <pre> * Optional. Indicates if generic web service is created through Cloud Functions * integration. Defaults to false. * is_cloud_function is deprecated. Cloud functions can be configured by * its uri as a regular web service now. * </pre> * * <code>bool is_cloud_function = 5 [deprecated = true, (.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearIsCloudFunction() { isCloudFunction_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.Fulfillment.GenericWebService) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.Fulfillment.GenericWebService) private static final com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService(); } public static com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GenericWebService> PARSER = new com.google.protobuf.AbstractParser<GenericWebService>() { @java.lang.Override public GenericWebService parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new GenericWebService(input, extensionRegistry); } }; public static com.google.protobuf.Parser<GenericWebService> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GenericWebService> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface FeatureOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2.Fulfillment.Feature) com.google.protobuf.MessageOrBuilder { /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The enum numeric value on the wire for type. */ int getTypeValue(); /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The type. */ com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type getType(); } /** * <pre> * Whether fulfillment is enabled for the specific feature. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment.Feature} */ public static final class Feature extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.Fulfillment.Feature) FeatureOrBuilder { private static final long serialVersionUID = 0L; // Use Feature.newBuilder() to construct. private Feature(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Feature() { type_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Feature(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Feature( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { int rawValue = input.readEnum(); type_ = rawValue; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_Feature_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_Feature_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.Feature.class, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder.class); } /** * <pre> * The type of the feature. * </pre> * * Protobuf enum {@code google.cloud.dialogflow.v2.Fulfillment.Feature.Type} */ public enum Type implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Feature type not specified. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ TYPE_UNSPECIFIED(0), /** * <pre> * Fulfillment is enabled for SmallTalk. * </pre> * * <code>SMALLTALK = 1;</code> */ SMALLTALK(1), UNRECOGNIZED(-1), ; /** * <pre> * Feature type not specified. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ public static final int TYPE_UNSPECIFIED_VALUE = 0; /** * <pre> * Fulfillment is enabled for SmallTalk. * </pre> * * <code>SMALLTALK = 1;</code> */ public static final int SMALLTALK_VALUE = 1; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Type valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Type forNumber(int value) { switch (value) { case 0: return TYPE_UNSPECIFIED; case 1: return SMALLTALK; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.dialogflow.v2.Fulfillment.Feature.getDescriptor().getEnumTypes().get(0); } private static final Type[] VALUES = values(); public static Type valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Type(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.dialogflow.v2.Fulfillment.Feature.Type) } public static final int TYPE_FIELD_NUMBER = 1; private int type_; /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The type. */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type getType() { @SuppressWarnings("deprecation") com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type result = com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.valueOf(type_); return result == null ? com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (type_ != com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, type_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (type_ != com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, type_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2.Fulfillment.Feature)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.Fulfillment.Feature other = (com.google.cloud.dialogflow.v2.Fulfillment.Feature) obj; if (type_ != other.type_) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dialogflow.v2.Fulfillment.Feature prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Whether fulfillment is enabled for the specific feature. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment.Feature} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.Fulfillment.Feature) com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_Feature_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_Feature_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.Feature.class, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.Fulfillment.Feature.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); type_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_Feature_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.Fulfillment.Feature.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature build() { com.google.cloud.dialogflow.v2.Fulfillment.Feature result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature buildPartial() { com.google.cloud.dialogflow.v2.Fulfillment.Feature result = new com.google.cloud.dialogflow.v2.Fulfillment.Feature(this); result.type_ = type_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2.Fulfillment.Feature) { return mergeFrom((com.google.cloud.dialogflow.v2.Fulfillment.Feature)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.Fulfillment.Feature other) { if (other == com.google.cloud.dialogflow.v2.Fulfillment.Feature.getDefaultInstance()) return this; if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2.Fulfillment.Feature parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2.Fulfillment.Feature) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int type_ = 0; /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; onChanged(); return this; } /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return The type. */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type getType() { @SuppressWarnings("deprecation") com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type result = com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.valueOf(type_); return result == null ? com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type.UNRECOGNIZED : result; } /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @param value The type to set. * @return This builder for chaining. */ public Builder setType(com.google.cloud.dialogflow.v2.Fulfillment.Feature.Type value) { if (value == null) { throw new NullPointerException(); } type_ = value.getNumber(); onChanged(); return this; } /** * <pre> * The type of the feature that enabled for fulfillment. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.Feature.Type type = 1;</code> * @return This builder for chaining. */ public Builder clearType() { type_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.Fulfillment.Feature) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.Fulfillment.Feature) private static final com.google.cloud.dialogflow.v2.Fulfillment.Feature DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.Fulfillment.Feature(); } public static com.google.cloud.dialogflow.v2.Fulfillment.Feature getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Feature> PARSER = new com.google.protobuf.AbstractParser<Feature>() { @java.lang.Override public Feature parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Feature(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Feature> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Feature> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private int fulfillmentCase_ = 0; private java.lang.Object fulfillment_; public enum FulfillmentCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { GENERIC_WEB_SERVICE(3), FULFILLMENT_NOT_SET(0); private final int value; private FulfillmentCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static FulfillmentCase valueOf(int value) { return forNumber(value); } public static FulfillmentCase forNumber(int value) { switch (value) { case 3: return GENERIC_WEB_SERVICE; case 0: return FULFILLMENT_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public FulfillmentCase getFulfillmentCase() { return FulfillmentCase.forNumber( fulfillmentCase_); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DISPLAY_NAME_FIELD_NUMBER = 2; private volatile java.lang.Object displayName_; /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The displayName. */ @java.lang.Override public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } } /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for displayName. */ @java.lang.Override public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GENERIC_WEB_SERVICE_FIELD_NUMBER = 3; /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> * @return Whether the genericWebService field is set. */ @java.lang.Override public boolean hasGenericWebService() { return fulfillmentCase_ == 3; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> * @return The genericWebService. */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService getGenericWebService() { if (fulfillmentCase_ == 3) { return (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_; } return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder getGenericWebServiceOrBuilder() { if (fulfillmentCase_ == 3) { return (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_; } return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } public static final int ENABLED_FIELD_NUMBER = 4; private boolean enabled_; /** * <pre> * Optional. Whether fulfillment is enabled. * </pre> * * <code>bool enabled = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enabled. */ @java.lang.Override public boolean getEnabled() { return enabled_; } public static final int FEATURES_FIELD_NUMBER = 5; private java.util.List<com.google.cloud.dialogflow.v2.Fulfillment.Feature> features_; /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2.Fulfillment.Feature> getFeaturesList() { return features_; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder> getFeaturesOrBuilderList() { return features_; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public int getFeaturesCount() { return features_.size(); } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.Feature getFeatures(int index) { return features_.get(index); } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder getFeaturesOrBuilder( int index) { return features_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_); } if (fulfillmentCase_ == 3) { output.writeMessage(3, (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_); } if (enabled_ != false) { output.writeBool(4, enabled_); } for (int i = 0; i < features_.size(); i++) { output.writeMessage(5, features_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_); } if (fulfillmentCase_ == 3) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_); } if (enabled_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, enabled_); } for (int i = 0; i < features_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, features_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2.Fulfillment)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.Fulfillment other = (com.google.cloud.dialogflow.v2.Fulfillment) obj; if (!getName() .equals(other.getName())) return false; if (!getDisplayName() .equals(other.getDisplayName())) return false; if (getEnabled() != other.getEnabled()) return false; if (!getFeaturesList() .equals(other.getFeaturesList())) return false; if (!getFulfillmentCase().equals(other.getFulfillmentCase())) return false; switch (fulfillmentCase_) { case 3: if (!getGenericWebService() .equals(other.getGenericWebService())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER; hash = (53 * hash) + getDisplayName().hashCode(); hash = (37 * hash) + ENABLED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnabled()); if (getFeaturesCount() > 0) { hash = (37 * hash) + FEATURES_FIELD_NUMBER; hash = (53 * hash) + getFeaturesList().hashCode(); } switch (fulfillmentCase_) { case 3: hash = (37 * hash) + GENERIC_WEB_SERVICE_FIELD_NUMBER; hash = (53 * hash) + getGenericWebService().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.Fulfillment parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dialogflow.v2.Fulfillment prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * By default, your agent responds to a matched intent with a static response. * As an alternative, you can provide a more dynamic response by using * fulfillment. When you enable fulfillment for an intent, Dialogflow responds * to that intent by calling a service that you define. For example, if an * end-user wants to schedule a haircut on Friday, your service can check your * database and respond to the end-user with availability information for * Friday. * For more information, see the [fulfillment * guide](https://cloud.google.com/dialogflow/docs/fulfillment-overview). * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.Fulfillment} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.Fulfillment) com.google.cloud.dialogflow.v2.FulfillmentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.Fulfillment.class, com.google.cloud.dialogflow.v2.Fulfillment.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.Fulfillment.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getFeaturesFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; displayName_ = ""; enabled_ = false; if (featuresBuilder_ == null) { features_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { featuresBuilder_.clear(); } fulfillmentCase_ = 0; fulfillment_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.FulfillmentProto.internal_static_google_cloud_dialogflow_v2_Fulfillment_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.Fulfillment.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment build() { com.google.cloud.dialogflow.v2.Fulfillment result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment buildPartial() { com.google.cloud.dialogflow.v2.Fulfillment result = new com.google.cloud.dialogflow.v2.Fulfillment(this); int from_bitField0_ = bitField0_; result.name_ = name_; result.displayName_ = displayName_; if (fulfillmentCase_ == 3) { if (genericWebServiceBuilder_ == null) { result.fulfillment_ = fulfillment_; } else { result.fulfillment_ = genericWebServiceBuilder_.build(); } } result.enabled_ = enabled_; if (featuresBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { features_ = java.util.Collections.unmodifiableList(features_); bitField0_ = (bitField0_ & ~0x00000001); } result.features_ = features_; } else { result.features_ = featuresBuilder_.build(); } result.fulfillmentCase_ = fulfillmentCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2.Fulfillment) { return mergeFrom((com.google.cloud.dialogflow.v2.Fulfillment)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.Fulfillment other) { if (other == com.google.cloud.dialogflow.v2.Fulfillment.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getDisplayName().isEmpty()) { displayName_ = other.displayName_; onChanged(); } if (other.getEnabled() != false) { setEnabled(other.getEnabled()); } if (featuresBuilder_ == null) { if (!other.features_.isEmpty()) { if (features_.isEmpty()) { features_ = other.features_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureFeaturesIsMutable(); features_.addAll(other.features_); } onChanged(); } } else { if (!other.features_.isEmpty()) { if (featuresBuilder_.isEmpty()) { featuresBuilder_.dispose(); featuresBuilder_ = null; features_ = other.features_; bitField0_ = (bitField0_ & ~0x00000001); featuresBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFeaturesFieldBuilder() : null; } else { featuresBuilder_.addAllMessages(other.features_); } } } switch (other.getFulfillmentCase()) { case GENERIC_WEB_SERVICE: { mergeGenericWebService(other.getGenericWebService()); break; } case FULFILLMENT_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2.Fulfillment parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2.Fulfillment) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int fulfillmentCase_ = 0; private java.lang.Object fulfillment_; public FulfillmentCase getFulfillmentCase() { return FulfillmentCase.forNumber( fulfillmentCase_); } public Builder clearFulfillment() { fulfillmentCase_ = 0; fulfillment_ = null; onChanged(); return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The name to set. * @return This builder for chaining. */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> * Required. The unique identifier of the fulfillment. * Supported formats: * - `projects/&lt;Project ID&gt;/agent/fulfillment` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent/fulfillment` * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object displayName_ = ""; /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The displayName. */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The bytes for displayName. */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The displayName to set. * @return This builder for chaining. */ public Builder setDisplayName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } displayName_ = value; onChanged(); return this; } /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearDisplayName() { displayName_ = getDefaultInstance().getDisplayName(); onChanged(); return this; } /** * <pre> * Optional. The human-readable name of the fulfillment, unique within the agent. * This field is not used for Fulfillment in an Environment. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The bytes for displayName to set. * @return This builder for chaining. */ public Builder setDisplayNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); displayName_ = value; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder> genericWebServiceBuilder_; /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> * @return Whether the genericWebService field is set. */ @java.lang.Override public boolean hasGenericWebService() { return fulfillmentCase_ == 3; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> * @return The genericWebService. */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService getGenericWebService() { if (genericWebServiceBuilder_ == null) { if (fulfillmentCase_ == 3) { return (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_; } return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } else { if (fulfillmentCase_ == 3) { return genericWebServiceBuilder_.getMessage(); } return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ public Builder setGenericWebService(com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService value) { if (genericWebServiceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } fulfillment_ = value; onChanged(); } else { genericWebServiceBuilder_.setMessage(value); } fulfillmentCase_ = 3; return this; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ public Builder setGenericWebService( com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder builderForValue) { if (genericWebServiceBuilder_ == null) { fulfillment_ = builderForValue.build(); onChanged(); } else { genericWebServiceBuilder_.setMessage(builderForValue.build()); } fulfillmentCase_ = 3; return this; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ public Builder mergeGenericWebService(com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService value) { if (genericWebServiceBuilder_ == null) { if (fulfillmentCase_ == 3 && fulfillment_ != com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance()) { fulfillment_ = com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.newBuilder((com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_) .mergeFrom(value).buildPartial(); } else { fulfillment_ = value; } onChanged(); } else { if (fulfillmentCase_ == 3) { genericWebServiceBuilder_.mergeFrom(value); } genericWebServiceBuilder_.setMessage(value); } fulfillmentCase_ = 3; return this; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ public Builder clearGenericWebService() { if (genericWebServiceBuilder_ == null) { if (fulfillmentCase_ == 3) { fulfillmentCase_ = 0; fulfillment_ = null; onChanged(); } } else { if (fulfillmentCase_ == 3) { fulfillmentCase_ = 0; fulfillment_ = null; } genericWebServiceBuilder_.clear(); } return this; } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder getGenericWebServiceBuilder() { return getGenericWebServiceFieldBuilder().getBuilder(); } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder getGenericWebServiceOrBuilder() { if ((fulfillmentCase_ == 3) && (genericWebServiceBuilder_ != null)) { return genericWebServiceBuilder_.getMessageOrBuilder(); } else { if (fulfillmentCase_ == 3) { return (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_; } return com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } } /** * <pre> * Configuration for a generic web service. * </pre> * * <code>.google.cloud.dialogflow.v2.Fulfillment.GenericWebService generic_web_service = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder> getGenericWebServiceFieldBuilder() { if (genericWebServiceBuilder_ == null) { if (!(fulfillmentCase_ == 3)) { fulfillment_ = com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.getDefaultInstance(); } genericWebServiceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService.Builder, com.google.cloud.dialogflow.v2.Fulfillment.GenericWebServiceOrBuilder>( (com.google.cloud.dialogflow.v2.Fulfillment.GenericWebService) fulfillment_, getParentForChildren(), isClean()); fulfillment_ = null; } fulfillmentCase_ = 3; onChanged();; return genericWebServiceBuilder_; } private boolean enabled_ ; /** * <pre> * Optional. Whether fulfillment is enabled. * </pre> * * <code>bool enabled = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enabled. */ @java.lang.Override public boolean getEnabled() { return enabled_; } /** * <pre> * Optional. Whether fulfillment is enabled. * </pre> * * <code>bool enabled = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The enabled to set. * @return This builder for chaining. */ public Builder setEnabled(boolean value) { enabled_ = value; onChanged(); return this; } /** * <pre> * Optional. Whether fulfillment is enabled. * </pre> * * <code>bool enabled = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearEnabled() { enabled_ = false; onChanged(); return this; } private java.util.List<com.google.cloud.dialogflow.v2.Fulfillment.Feature> features_ = java.util.Collections.emptyList(); private void ensureFeaturesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { features_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2.Fulfillment.Feature>(features_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.Feature, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder, com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder> featuresBuilder_; /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Fulfillment.Feature> getFeaturesList() { if (featuresBuilder_ == null) { return java.util.Collections.unmodifiableList(features_); } else { return featuresBuilder_.getMessageList(); } } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public int getFeaturesCount() { if (featuresBuilder_ == null) { return features_.size(); } else { return featuresBuilder_.getCount(); } } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.Feature getFeatures(int index) { if (featuresBuilder_ == null) { return features_.get(index); } else { return featuresBuilder_.getMessage(index); } } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder setFeatures( int index, com.google.cloud.dialogflow.v2.Fulfillment.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.set(index, value); onChanged(); } else { featuresBuilder_.setMessage(index, value); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder setFeatures( int index, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.set(index, builderForValue.build()); onChanged(); } else { featuresBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder addFeatures(com.google.cloud.dialogflow.v2.Fulfillment.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.add(value); onChanged(); } else { featuresBuilder_.addMessage(value); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder addFeatures( int index, com.google.cloud.dialogflow.v2.Fulfillment.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.add(index, value); onChanged(); } else { featuresBuilder_.addMessage(index, value); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder addFeatures( com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.add(builderForValue.build()); onChanged(); } else { featuresBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder addFeatures( int index, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.add(index, builderForValue.build()); onChanged(); } else { featuresBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder addAllFeatures( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.Fulfillment.Feature> values) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, features_); onChanged(); } else { featuresBuilder_.addAllMessages(values); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder clearFeatures() { if (featuresBuilder_ == null) { features_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { featuresBuilder_.clear(); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder removeFeatures(int index) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.remove(index); onChanged(); } else { featuresBuilder_.remove(index); } return this; } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder getFeaturesBuilder( int index) { return getFeaturesFieldBuilder().getBuilder(index); } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder getFeaturesOrBuilder( int index) { if (featuresBuilder_ == null) { return features_.get(index); } else { return featuresBuilder_.getMessageOrBuilder(index); } } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder> getFeaturesOrBuilderList() { if (featuresBuilder_ != null) { return featuresBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(features_); } } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder addFeaturesBuilder() { return getFeaturesFieldBuilder().addBuilder( com.google.cloud.dialogflow.v2.Fulfillment.Feature.getDefaultInstance()); } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder addFeaturesBuilder( int index) { return getFeaturesFieldBuilder().addBuilder( index, com.google.cloud.dialogflow.v2.Fulfillment.Feature.getDefaultInstance()); } /** * <pre> * Optional. The field defines whether the fulfillment is enabled for certain features. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Fulfillment.Feature features = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder> getFeaturesBuilderList() { return getFeaturesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.Feature, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder, com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder> getFeaturesFieldBuilder() { if (featuresBuilder_ == null) { featuresBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Fulfillment.Feature, com.google.cloud.dialogflow.v2.Fulfillment.Feature.Builder, com.google.cloud.dialogflow.v2.Fulfillment.FeatureOrBuilder>( features_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); features_ = null; } return featuresBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.Fulfillment) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.Fulfillment) private static final com.google.cloud.dialogflow.v2.Fulfillment DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.Fulfillment(); } public static com.google.cloud.dialogflow.v2.Fulfillment getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Fulfillment> PARSER = new com.google.protobuf.AbstractParser<Fulfillment>() { @java.lang.Override public Fulfillment parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Fulfillment(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Fulfillment> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Fulfillment> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.Fulfillment getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Targeted by JavaCPP version 1.5.2-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.tensorflow; import org.bytedeco.tensorflow.Allocator; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.tensorflow.global.tensorflow.*; // ------------------------------------------------------------------- @Namespace("tensorflow") @NoOffset @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class) public class NodeDef_ExperimentalDebugInfo extends MessageLite { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public NodeDef_ExperimentalDebugInfo(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public NodeDef_ExperimentalDebugInfo(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public NodeDef_ExperimentalDebugInfo position(long position) { return (NodeDef_ExperimentalDebugInfo)super.position(position); } public NodeDef_ExperimentalDebugInfo() { super((Pointer)null); allocate(); } private native void allocate(); public NodeDef_ExperimentalDebugInfo(@Const @ByRef NodeDef_ExperimentalDebugInfo from) { super((Pointer)null); allocate(from); } private native void allocate(@Const @ByRef NodeDef_ExperimentalDebugInfo from); public native @ByRef @Name("operator =") NodeDef_ExperimentalDebugInfo put(@Const @ByRef NodeDef_ExperimentalDebugInfo from); // #if LANG_CXX11 // #endif public native Arena GetArena(); public native Pointer GetMaybeArenaPointer(); public static native @Cast("const google::protobuf::Descriptor*") Pointer descriptor(); public static native @Const @ByRef NodeDef_ExperimentalDebugInfo default_instance(); public static native void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY public static native @Const NodeDef_ExperimentalDebugInfo internal_default_instance(); @MemberGetter public static native int kIndexInFileMessages(); public static final int kIndexInFileMessages = kIndexInFileMessages(); public native void UnsafeArenaSwap(NodeDef_ExperimentalDebugInfo other); public native void Swap(NodeDef_ExperimentalDebugInfo other); // implements Message ---------------------------------------------- public native NodeDef_ExperimentalDebugInfo New(); public native NodeDef_ExperimentalDebugInfo New(Arena arena); public native void CopyFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from); public native void MergeFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from); public native void CopyFrom(@Const @ByRef NodeDef_ExperimentalDebugInfo from); public native void MergeFrom(@Const @ByRef NodeDef_ExperimentalDebugInfo from); public native void Clear(); public native @Cast("bool") boolean IsInitialized(); public native @Cast("size_t") long ByteSizeLong(); // #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER // #else public native @Cast("bool") boolean MergePartialFromCodedStream( CodedInputStream input); // #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER public native void SerializeWithCachedSizes( CodedOutputStream output); public native @Cast("google::protobuf::uint8*") BytePointer InternalSerializeWithCachedSizesToArray( @Cast("google::protobuf::uint8*") BytePointer target); public native @Cast("google::protobuf::uint8*") ByteBuffer InternalSerializeWithCachedSizesToArray( @Cast("google::protobuf::uint8*") ByteBuffer target); public native @Cast("google::protobuf::uint8*") byte[] InternalSerializeWithCachedSizesToArray( @Cast("google::protobuf::uint8*") byte[] target); public native int GetCachedSize(); public native @ByVal @Cast("google::protobuf::Metadata*") Pointer GetMetadata(); // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated string original_node_names = 1; public native int original_node_names_size(); public native void clear_original_node_names(); @MemberGetter public static native int kOriginalNodeNamesFieldNumber(); public static final int kOriginalNodeNamesFieldNumber = kOriginalNodeNamesFieldNumber(); public native @StdString BytePointer original_node_names(int index); public native @StdString @Cast({"char*", "std::string*"}) BytePointer mutable_original_node_names(int index); public native void set_original_node_names(int index, @StdString BytePointer value); public native void set_original_node_names(int index, @StdString String value); // #if LANG_CXX11 // #endif public native void set_original_node_names(int index, @Cast("const char*") BytePointer value, @Cast("size_t") long size); public native void set_original_node_names(int index, String value, @Cast("size_t") long size); public native @StdString @Cast({"char*", "std::string*"}) BytePointer add_original_node_names(); public native void add_original_node_names(@StdString BytePointer value); public native void add_original_node_names(@StdString String value); // #if LANG_CXX11 // #endif public native void add_original_node_names(@Cast("const char*") BytePointer value, @Cast("size_t") long size); public native void add_original_node_names(String value, @Cast("size_t") long size); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // THIS CODE IS AUTOMATICALLY GENERATED. DO NOT EDIT. package org.apache.kafka.common.message; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.BinaryNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.LongNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Arrays; import org.apache.kafka.common.protocol.MessageUtil; import static org.apache.kafka.common.message.ExpireDelegationTokenRequestData.*; public class ExpireDelegationTokenRequestDataJsonConverter { public static ExpireDelegationTokenRequestData read(JsonNode _node, short _version) { ExpireDelegationTokenRequestData _object = new ExpireDelegationTokenRequestData(); JsonNode _hmacNode = _node.get("hmac"); if (_hmacNode == null) { throw new RuntimeException("ExpireDelegationTokenRequestData: unable to locate field 'hmac', which is mandatory in version " + _version); } else { _object.hmac = MessageUtil.jsonNodeToBinary(_hmacNode, "ExpireDelegationTokenRequestData"); } JsonNode _expiryTimePeriodMsNode = _node.get("expiryTimePeriodMs"); if (_expiryTimePeriodMsNode == null) { throw new RuntimeException("ExpireDelegationTokenRequestData: unable to locate field 'expiryTimePeriodMs', which is mandatory in version " + _version); } else { _object.expiryTimePeriodMs = MessageUtil.jsonNodeToLong(_expiryTimePeriodMsNode, "ExpireDelegationTokenRequestData"); } return _object; } public static JsonNode write(ExpireDelegationTokenRequestData _object, short _version, boolean _serializeRecords) { ObjectNode _node = new ObjectNode(JsonNodeFactory.instance); _node.set("hmac", new BinaryNode(Arrays.copyOf(_object.hmac, _object.hmac.length))); _node.set("expiryTimePeriodMs", new LongNode(_object.expiryTimePeriodMs)); return _node; } public static JsonNode write(ExpireDelegationTokenRequestData _object, short _version) { return write(_object, _version, true); } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl; import com.intellij.ide.highlighter.HighlighterFactory; import com.intellij.lang.Language; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileEditor.impl.text.TextEditorPsiDataProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.IncorrectOperationException; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import javax.swing.*; import java.awt.*; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; final class TestEditorManagerImpl extends FileEditorManagerEx implements Disposable { private static final Logger LOG = Logger.getInstance(TestEditorManagerImpl.class); private final TestEditorSplitter myTestEditorSplitter = new TestEditorSplitter(); private final Project myProject; private int counter; private final Map<VirtualFile, Editor> myVirtualFile2Editor = new HashMap<>(); private VirtualFile myActiveFile; private static final MyLightVirtualFile LIGHT_VIRTUAL_FILE = new MyLightVirtualFile(); private static class MyLightVirtualFile extends LightVirtualFile { MyLightVirtualFile() {super("Dummy.java");} void clearUserDataOnDispose() { clearUserData(); } } TestEditorManagerImpl(@NotNull Project project) { myProject = project; registerExtraEditorDataProvider(new TextEditorPsiDataProvider(), null); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { if (project == myProject) { closeAllFiles(); } } }); project.getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void before(@NotNull List<? extends @NotNull VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFileDeleteEvent) { for (VirtualFile file : getOpenFiles()) { if (VfsUtilCore.isAncestor(((VFileDeleteEvent)event).getFile(), file, false)) { closeFile(file); } } } } } }); } @Override @NotNull public Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull final VirtualFile file, final boolean focusEditor, boolean searchForSplitter) { return openFileInCommand(new OpenFileDescriptor(myProject, file)); } @NotNull private Pair<FileEditor[], FileEditorProvider[]> openFileImpl3(@NotNull FileEditorNavigatable openFileDescriptor) { VirtualFile file = openFileDescriptor.getFile(); boolean isNewEditor = !myVirtualFile2Editor.containsKey(file); // for non-text editors. uml, etc final FileEditorProvider provider = file.getUserData(FileEditorProvider.KEY); Pair<FileEditor[], FileEditorProvider[]> result; if (provider != null && provider.accept(getProject(), file)) { result = Pair.create(new FileEditor[]{provider.createEditor(getProject(), file)}, new FileEditorProvider[]{provider}); } else { //text editor Editor editor = doOpenTextEditor(openFileDescriptor); final FileEditor fileEditor = TextEditorProvider.getInstance().getTextEditor(editor); final FileEditorProvider fileEditorProvider = getProvider(); result = Pair.create(new FileEditor[]{fileEditor}, new FileEditorProvider[]{fileEditorProvider}); } modifyTabWell(() -> { myTestEditorSplitter.openAndFocusTab(file, result.first[0], result.second[0]); if (isNewEditor) { eventPublisher().fileOpened(this, file); } }); return result; } private void modifyTabWell(@NotNull Runnable tabWellModification) { if (myProject.isDisposed()) return; FileEditor lastFocusedEditor = myTestEditorSplitter.getFocusedFileEditor(); VirtualFile lastFocusedFile = myTestEditorSplitter.getFocusedFile(); FileEditorProvider oldProvider = myTestEditorSplitter.getProviderFromFocused(); tabWellModification.run(); FileEditor currentlyFocusedEditor = myTestEditorSplitter.getFocusedFileEditor(); VirtualFile currentlyFocusedFile = myTestEditorSplitter.getFocusedFile(); FileEditorProvider newProvider = myTestEditorSplitter.getProviderFromFocused(); final FileEditorManagerEvent event = new FileEditorManagerEvent(this, lastFocusedFile, lastFocusedEditor, oldProvider, currentlyFocusedFile, currentlyFocusedEditor, newProvider); eventPublisher().selectionChanged(event); } @NotNull private FileEditorManagerListener eventPublisher() { return getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); } @NotNull @Override public Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor, @NotNull EditorWindow window) { return openFileWithProviders(file, focusEditor, false); } @Override public boolean isInsideChange() { return false; } @NotNull @Override public ActionCallback notifyPublisher(@NotNull Runnable runnable) { runnable.run(); return ActionCallback.DONE; } @Override public EditorsSplitters getSplittersFor(Component c) { return null; } @Override public void createSplitter(int orientation, EditorWindow window) { String containerName = createNewTabbedContainerName(); myTestEditorSplitter.setActiveTabGroup(containerName); } private String createNewTabbedContainerName() { counter++; return "SplitTabContainer" + counter; } @Override public void changeSplitterOrientation() { } @Override public boolean isInSplitter() { return false; } @Override public boolean hasOpenedFile() { return false; } @Override public VirtualFile getCurrentFile() { return myActiveFile; } @Override public FileEditorWithProvider getSelectedEditorWithProvider(@NotNull VirtualFile file) { return null; } @Override public boolean isChanged(@NotNull EditorComposite editor) { return false; } @Override public EditorWindow getNextWindow(@NotNull EditorWindow window) { return null; } @Override public EditorWindow getPrevWindow(@NotNull EditorWindow window) { return null; } @Override public void addTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component) { } @Override public void removeTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component) { } @Override public void addBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component) { } @Override public void removeBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component) { } @Override public void closeAllFiles() { for (VirtualFile file : getOpenFiles()) { closeFile(file); } } private static FileEditorProvider getProvider() { return new FileEditorProvider() { @Override public boolean accept(@NotNull Project project, @NotNull VirtualFile file) { return false; } @Override @NotNull public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) { throw new IncorrectOperationException(); } @Override public void disposeEditor(@NotNull FileEditor editor) { } @Override @NotNull public FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file) { throw new IncorrectOperationException(); } @Override @NotNull public String getEditorTypeId() { return ""; } @Override @NotNull public FileEditorPolicy getPolicy() { throw new IncorrectOperationException(); } }; } @Override public EditorWindow getCurrentWindow() { return null; } @NotNull @Override public Promise<EditorWindow> getActiveWindow() { return Promises.resolvedPromise(); } @Override public void setCurrentWindow(EditorWindow window) { } @Override public VirtualFile getFile(@NotNull FileEditor editor) { return LIGHT_VIRTUAL_FILE; } @Override public void updateFilePresentation(@NotNull VirtualFile file) { } @Override public void unsplitWindow() { } @Override public void unsplitAllWindow() { } @Override public EditorWindow @NotNull [] getWindows() { return new EditorWindow[0]; } @Override public FileEditor getSelectedEditor(@NotNull VirtualFile file) { final Editor editor = getEditor(file); if (editor != null) { return TextEditorProvider.getInstance().getTextEditor(editor); } Pair<FileEditor, FileEditorProvider> editorAndProvider = myTestEditorSplitter.getEditorAndProvider(file); if (editorAndProvider != null) { return editorAndProvider.first; } return null; } @Override public boolean isFileOpen(@NotNull VirtualFile file) { return getEditor(file) != null; } @Override public FileEditor @NotNull [] getEditors(@NotNull VirtualFile file) { FileEditor e = getSelectedEditor(file); if (e == null) return FileEditor.EMPTY_ARRAY; return new FileEditor[] {e}; } @Override public FileEditor @NotNull [] getAllEditors(@NotNull VirtualFile file) { return getEditors(file); } @Override public VirtualFile @NotNull [] getSiblings(@NotNull VirtualFile file) { throw new UnsupportedOperationException(); } @Override public void dispose() { closeAllFiles(); LIGHT_VIRTUAL_FILE.clearUserDataOnDispose(); } @Override public void closeFile(@NotNull final VirtualFile file) { Editor editor = myVirtualFile2Editor.remove(file); if (editor != null){ TextEditorProvider editorProvider = TextEditorProvider.getInstance(); editorProvider.disposeEditor(editorProvider.getTextEditor(editor)); EditorFactory.getInstance().releaseEditor(editor); if (!myProject.isDisposed()) { eventPublisher().fileClosed(this, file); } } if (Comparing.equal(file, myActiveFile)) { myActiveFile = null; } modifyTabWell(() -> myTestEditorSplitter.closeFile(file)); } @Override public void closeFile(@NotNull VirtualFile file, @NotNull EditorWindow window) { closeFile(file); } @Override public VirtualFile @NotNull [] getSelectedFiles() { return myActiveFile == null ? VirtualFile.EMPTY_ARRAY : new VirtualFile[]{myActiveFile}; } @Override public FileEditor @NotNull [] getSelectedEditors() { return myActiveFile == null ? FileEditor.EMPTY_ARRAY : getEditors(myActiveFile); } @Override public Editor getSelectedTextEditor() { return myActiveFile != null ? getEditor(myActiveFile) : null; } @Override public JComponent getComponent() { return new JLabel(); } @Override public VirtualFile @NotNull [] getOpenFiles() { return VfsUtilCore.toVirtualFileArray(myVirtualFile2Editor.keySet()); } public Editor getEditor(VirtualFile file) { return myVirtualFile2Editor.get(file); } @Override public FileEditor @NotNull [] getAllEditors() { FileEditor[] result = new FileEditor[myVirtualFile2Editor.size()]; int i = 0; for (Map.Entry<VirtualFile, Editor> entry : myVirtualFile2Editor.entrySet()) { TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(entry.getValue()); result[i++] = textEditor; } return result; } @Override public Editor openTextEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor) { Pair<FileEditor[], FileEditorProvider[]> pair = openFileInCommand(descriptor); for (FileEditor editor : pair.first) { if (editor instanceof TextEditor) { return ((TextEditor)editor).getEditor(); } } return null; } @NotNull private Pair<FileEditor[], FileEditorProvider[]> openFileInCommand(@NotNull FileEditorNavigatable descriptor) { Ref<Pair<FileEditor[], FileEditorProvider[]>> result = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> result.set(openFileImpl3(descriptor)), "", null); return result.get(); } @NotNull private Editor doOpenTextEditor(@NotNull FileEditorNavigatable descriptor) { VirtualFile file = descriptor.getFile(); Editor editor = myVirtualFile2Editor.get(file); if (editor == null) { Document document = FileDocumentManager.getInstance().getDocument(file); LOG.assertTrue(document != null, file); EditorFactory editorFactory = EditorFactory.getInstance(); editor = editorFactory.createEditor(document, myProject); try { EditorHighlighter highlighter = HighlighterFactory.createHighlighter(myProject, file); Language language = TextEditorImpl.getDocumentLanguage(editor); editor.getSettings().setLanguageSupplier(() -> language); EditorEx editorEx = (EditorEx)editor; editorEx.setHighlighter(highlighter); editorEx.setFile(file); } catch (Throwable e) { editorFactory.releaseEditor(editor); throw e; } myVirtualFile2Editor.put(file, editor); } editor.getSelectionModel().removeSelection(); if (descriptor instanceof OpenFileDescriptor) { ((OpenFileDescriptor)descriptor).navigateIn(editor); } myActiveFile = file; return editor; } @Override @NotNull public List<FileEditor> openFileEditor(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { Pair<FileEditor[], FileEditorProvider[]> pair = openFileInCommand(descriptor); return Arrays.asList(pair.first); } @Override @NotNull public Project getProject() { return myProject; } @Override public JComponent getPreferredFocusedComponent() { throw new UnsupportedOperationException(); } @Override @NotNull public Pair<FileEditor[], FileEditorProvider[]> getEditorsWithProviders(@NotNull VirtualFile file) { Pair<FileEditor, FileEditorProvider> editorAndProvider = myTestEditorSplitter.getEditorAndProvider(file); FileEditor[] fileEditor = FileEditor.EMPTY_ARRAY; FileEditorProvider[] fileEditorProvider= new FileEditorProvider[0]; if (editorAndProvider != null) { fileEditor = new FileEditor[] {editorAndProvider.first}; fileEditorProvider = new FileEditorProvider[]{editorAndProvider.second}; } return Pair.create(fileEditor, fileEditorProvider); } @Override public int getWindowSplitCount() { return 0; } @Override public boolean hasSplitOrUndockedWindows() { return false; } @NotNull @Override public EditorsSplitters getSplitters() { throw new IncorrectOperationException(); } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { return ActionCallback.DONE; } @Override public void setSelectedEditor(@NotNull VirtualFile file, @NotNull String fileEditorProviderId) { if (myVirtualFile2Editor.containsKey(file)) { modifyTabWell(() -> { myActiveFile = file; myTestEditorSplitter.setFocusedFile(file); }); } } }
/** * Copyright (C) 2011 ConnId (connid-dev@googlegroups.com) * * 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 net.tirasa.connid.bundles.ad.crud; import static org.junit.Assert.*; import net.tirasa.connid.bundles.ad.ADConfiguration; import net.tirasa.connid.bundles.ad.AbstractTest; import org.identityconnectors.framework.common.objects.AttributeInfo; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.ObjectClassInfo; import org.identityconnectors.framework.common.objects.Schema; import org.junit.Test; public class SchemaTest extends AbstractTest { @Test public void schema() { AbstractTest.init(); final Schema schema = connector.schema(); assertNotNull(schema); final ObjectClassInfo info = schema.findObjectClassInfo(ObjectClass.ACCOUNT_NAME); assertNotNull(info); assertNotNull(info.getAttributeInfo()); assertFalse(info.getAttributeInfo().isEmpty()); assertNotNull(schema.getOperationOptionInfo()); boolean sddl = false; boolean givenname = false; for (AttributeInfo attrInfo : info.getAttributeInfo()) { if (ADConfiguration.UCCP_FLAG.equals(attrInfo.getName())) { sddl = true; assertEquals(Boolean.class, attrInfo.getType()); } if ("givenName".equalsIgnoreCase(attrInfo.getName())) { givenname = true; assertEquals(String.class, attrInfo.getType()); } } assertTrue(sddl && givenname); } }
/** * Copyright 2021 Shulie Technology, Co.Ltd * Email: shulie@shulie.io * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.shulie.instrument.simulator.api.listener.ext; import com.shulie.instrument.simulator.api.event.EventType; import com.shulie.instrument.simulator.api.listener.Listeners; /** * 正在观察匹配构建器 * * @author xiaobin.zfb|xiaobin@shulie.io * @since 2020/10/23 10:47 下午 */ public interface IWatchingMatchBuilder { /** * 添加渲染进度监听器,可以添加多个 * <p> * 用于观察{@link #onWatching(Listeners)}和{@link #onWatching(Listeners, EventType...)}的渲染进度 * </p> * * @param progress 渲染进度监听器 * @return IBuildingForWatching */ IWatchingMatchBuilder withProgress(Progress progress); /** * 观察行为内部的方法调用 * 调用之后, * <ul> * <li>{@link AdviceListener#beforeCall(Advice, int, boolean, String, String, String)}</li> * <li>{@link AdviceListener#afterCallReturning(Advice, int, boolean, String, String, String)}</li> * <li>{@link AdviceListener#afterCallThrowing(Advice, int, boolean, String, String, String, Throwable)}</li> * </ul> * <p> * 将会被触发 * * @return IBuildingForWatching */ IWatchingMatchBuilder withCall(); /** * 观察行为内部的行调用 * 调用之后, * <ul> * <li>{@link AdviceListener#beforeLine(Advice, int)}</li> * </ul> * 将会被触发 * * @return IBuildingForWatching */ IWatchingMatchBuilder withLine(); /** * 使用通知监听器观察 * * @param listeners 通知监听器定义 * @return EventWatcher */ void onWatching(Listeners listeners) throws Throwable; /** * 使用事件监听器观察 * * @param listeners 事件监听器定义 * @param eventEventTypeArray 需要监听的事件 * @return EventWatcher */ void onWatching(Listeners listeners, EventType... eventEventTypeArray) throws Throwable; }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.api.management.mbean; import org.apache.camel.api.management.ManagedAttribute; public interface ManagedRemovePropertyMBean extends ManagedProcessorMBean { @ManagedAttribute(description = "Name of exchange property to remove") String getPropertyName(); }
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ package com.ning.http.client; import com.ning.http.client.Request.EntityWriter; import com.ning.http.client.logging.LogManager; import com.ning.http.client.logging.Logger; import com.ning.http.client.providers.jdk.JDKAsyncHttpProvider; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Map; import java.util.concurrent.Future; /** * This class support asynchronous and synchronous HTTP request. * * To execute synchronous HTTP request, you just need to do * {@code * AsyncHttpClient c = new AsyncHttpClient(); * Future<Response> f = c.prepareGet("http://www.ning.com/").execute(); * } * * The code above will block until the response is fully received. To execute asynchronous HTTP request, you * create an {@link AsyncHandler} or its abstract implementation, {@link com.ning.http.client.AsyncCompletionHandler} * * {@code * AsyncHttpClient c = new AsyncHttpClient(); * Future<Response> f = c.prepareGet("http://www.ning.com/").execute(new AsyncCompletionHandler<Response>() &#123; * * &#64;Override * public Response onCompleted(Response response) throws IOException &#123; * // Do something * return response; * &#125; * * &#64;Override * public void onThrowable(Throwable t) &#123; * &#125; * &#125;); * Response response = f.get(); * * // We are just interested to retrieve the status code. * Future<Integer> f = c.prepareGet("http://www.ning.com/").execute(new AsyncCompletionHandler<Integer>() &#123; * * &#64;Override * public Integer onCompleted(Response response) throws IOException &#123; * // Do something * return response.getStatusCode(); * &#125; * * &#64;Override * public void onThrowable(Throwable t) &#123; * &#125; * &#125;); * Integer statusCode = f.get(); * } * The {@link AsyncCompletionHandler#onCompleted(com.ning.http.client.Response)} will be invoked once the http response has been fully read, which include * the http headers and the response body. Note that the entire response will be buffered in memory. * * You can also have more control about the how the response is asynchronously processed by using a {@link AsyncHandler} * {@code * AsyncHttpClient c = new AsyncHttpClient(); * Future<String> f = c.prepareGet("http://www.ning.com/").execute(new AsyncHandler<String>() &#123; * private StringBuilder builder = new StringBuilder(); * * &#64;Override * public STATE onStatusReceived(HttpResponseStatus s) throws Exception &#123; * // return STATE.CONTINUE or STATE.ABORT * return STATE.CONTINUE * } * * &#64;Override * public STATE onHeadersReceived(HttpResponseHeaders bodyPart) throws Exception &#123; * // return STATE.CONTINUE or STATE.ABORT * return STATE.CONTINUE * * } * &#64;Override * * public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception &#123; * builder.append(new String(bodyPart)); * // return STATE.CONTINUE or STATE.ABORT * return STATE.CONTINUE * &#125; * * &#64;Override * public String onCompleted() throws Exception &#123; * // Will be invoked once the response has been fully read or a ResponseComplete exception * // has been thrown. * return builder.toString(); * &#125; * * &#64;Override * public void onThrowable(Throwable t) &#123; * &#125; * &#125;); * * String bodyResponse = f.get(); * } * From any {@link HttpContent} sub classes, you can asynchronously process the response status,headers and body and decide when to * stop the processing the response by throwing a new {link ResponseComplete} at any moment. * * This class can also be used without the need of {@link AsyncHandler}</p> * {@code * AsyncHttpClient c = new AsyncHttpClient(); * Future<Response> f = c.prepareGet(TARGET_URL).execute(); * Response r = f.get(); * } * * Finally, you can configure the AsyncHttpClient using an {@link AsyncHttpClientConfig} instance</p> * {@code * AsyncHttpClient c = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(...).build()); * Future<Response> f = c.prepareGet(TARGET_URL).execute(); * Response r = f.get(); * } * * An instance of this class will cache every HTTP 1.1 connections and close them when the {@link AsyncHttpClientConfig#getIdleConnectionTimeoutInMs()} * expires. This object can hold many persistent connections to different host. * */ public class AsyncHttpClient { private final static String DEFAULT_PROVIDER = "com.ning.http.client.providers.netty.NettyAsyncHttpProvider"; private final AsyncHttpProvider<?> httpProvider; private final AsyncHttpClientConfig config; private final static Logger logger = LogManager.getLogger(AsyncHttpClient.class); /** * Default signature calculator to use for all requests constructed by this client instance. * * @since 1.1 */ protected SignatureCalculator signatureCalculator; /** * Create a new HTTP Asynchronous Client using the default {@link AsyncHttpClientConfig} configuration. The * default {@link AsyncHttpProvider} will be used ({@link com.ning.http.client.providers.netty.NettyAsyncHttpProvider} */ public AsyncHttpClient() { this(new AsyncHttpClientConfig.Builder().build()); } /** * Create a new HTTP Asynchronous Client using an implementation of {@link AsyncHttpProvider} and * the default {@link AsyncHttpClientConfig} configuration. * @param provider a {@link AsyncHttpProvider} */ public AsyncHttpClient(AsyncHttpProvider<?> provider) { this(provider,new AsyncHttpClientConfig.Builder().build()); } /** * Create a new HTTP Asynchronous Client using a {@link AsyncHttpClientConfig} configuration and the * {@link #DEFAULT_PROVIDER} * @param config a {@link AsyncHttpClientConfig} */ public AsyncHttpClient(AsyncHttpClientConfig config) { this(loadDefaultProvider(DEFAULT_PROVIDER, config),config); } /** * Create a new HTTP Asynchronous Client using a {@link AsyncHttpClientConfig} configuration and * and a {@link AsyncHttpProvider}. * @param config a {@link AsyncHttpClientConfig} * @param httpProvider a {@link AsyncHttpProvider} */ public AsyncHttpClient(AsyncHttpProvider<?> httpProvider, AsyncHttpClientConfig config) { this.config = config; this.httpProvider = httpProvider; } /** * Create a new HTTP Asynchronous Client using a {@link AsyncHttpClientConfig} configuration and * and a AsyncHttpProvider class' name. * @param config a {@link AsyncHttpClientConfig} * @param providerClass a {@link AsyncHttpProvider} */ public AsyncHttpClient(String providerClass, AsyncHttpClientConfig config) { this.config = new AsyncHttpClientConfig.Builder().build(); this.httpProvider = loadDefaultProvider(providerClass,config); } public class BoundRequestBuilder extends RequestBuilderBase<BoundRequestBuilder> { /** * Calculator used for calculating request signature for the request being * built, if any. */ protected SignatureCalculator signatureCalculator; /** * URL used as the base, not including possibly query parameters. Needed for * signature calculation */ protected String baseURL; private BoundRequestBuilder(String reqType) { super(BoundRequestBuilder.class, reqType); } private BoundRequestBuilder(Request prototype) { super(BoundRequestBuilder.class, prototype); } public <T> Future<T> execute(AsyncHandler<T> handler) throws IOException { return AsyncHttpClient.this.executeRequest(build(), handler); } public Future<Response> execute() throws IOException { return AsyncHttpClient.this.executeRequest(build(), new AsyncCompletionHandlerBase()); } // Note: For now we keep the delegates in place even though they are not needed // since otherwise Clojure (and maybe other languages) won't be able to // access these methods - see Clojure tickets 126 and 259 @Override public BoundRequestBuilder addBodyPart(Part part) throws IllegalArgumentException { return super.addBodyPart(part); } @Override public BoundRequestBuilder addCookie(Cookie cookie) { return super.addCookie(cookie); } @Override public BoundRequestBuilder addHeader(String name, String value) { return super.addHeader(name, value); } @Override public BoundRequestBuilder addParameter(String key, String value) throws IllegalArgumentException { return super.addParameter(key, value); } @Override public BoundRequestBuilder addQueryParameter(String name, String value) { return super.addQueryParameter(name, value); } @Override public Request build() { /* Let's first calculate and inject signature, before finalizing actual build * (order does not matter with current implementation but may in future) */ if (signatureCalculator != null) { String url = baseURL; // Should not include query parameters, ensure: int i = url.indexOf('?'); if (i >= 0) { url = url.substring(0, i); } signatureCalculator.calculateAndAddSignature(baseURL, request, this); } return super.build(); } @Override public BoundRequestBuilder setBody(byte[] data) throws IllegalArgumentException { return super.setBody(data); } @Override public BoundRequestBuilder setBody(EntityWriter dataWriter, long length) throws IllegalArgumentException { return super.setBody(dataWriter, length); } @Override public BoundRequestBuilder setBody(EntityWriter dataWriter) { return super.setBody(dataWriter); } @Override public BoundRequestBuilder setBody(InputStream stream) throws IllegalArgumentException { return super.setBody(stream); } @Override public BoundRequestBuilder setBody(String data) throws IllegalArgumentException { return super.setBody(data); } @Override public BoundRequestBuilder setHeader(String name, String value) { return super.setHeader(name, value); } @Override public BoundRequestBuilder setHeaders(FluentCaseInsensitiveStringsMap headers) { return super.setHeaders(headers); } @Override public BoundRequestBuilder setHeaders(Map<String, Collection<String>> headers) { return super.setHeaders(headers); } @Override public BoundRequestBuilder setParameters(Map<String, Collection<String>> parameters) throws IllegalArgumentException { return super.setParameters(parameters); } @Override public BoundRequestBuilder setParameters(FluentStringsMap parameters) throws IllegalArgumentException { return super.setParameters(parameters); } @Override public BoundRequestBuilder setUrl(String url) { baseURL = url; return super.setUrl(url); } @Override public BoundRequestBuilder setVirtualHost(String virtualHost) { return super.setVirtualHost(virtualHost); } public BoundRequestBuilder setSignatureCalculator(SignatureCalculator signatureCalculator) { this.signatureCalculator = signatureCalculator; return this; } } /** * Return the asynchronous {@link com.ning.http.client.AsyncHttpProvider} * @return an {@link com.ning.http.client.AsyncHttpProvider} */ public AsyncHttpProvider<?> getProvider() { return httpProvider; } /** * Close the underlying connections. */ public void close() { httpProvider.close(); } @Override protected void finalize() throws Throwable { close(); super.finalize(); } /** * Return the {@link com.ning.http.client.AsyncHttpClientConfig} * @return {@link com.ning.http.client.AsyncHttpClientConfig} */ public AsyncHttpClientConfig getConfig(){ return config; } /** * Set default signature calculator to use for requests build by this client instance */ public void setSignatureCalculator(SignatureCalculator signatureCalculator) { this.signatureCalculator = signatureCalculator; } /** * Prepare an HTTP client GET request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareGet(String url) { return requestBuilder("GET", url); } /** * Prepare an HTTP client CONNECT request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareConnect(String url) { return requestBuilder("CONNECT", url); } /** * Prepare an HTTP client OPTIONS request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareOptions(String url) { return requestBuilder("OPTIONS", url); } /** * Prepare an HTTP client HEAD request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareHead(String url) { return requestBuilder("HEAD", url); } /** * Prepare an HTTP client POST request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder preparePost(String url) { return requestBuilder("POST", url); } /** * Prepare an HTTP client PUT request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder preparePut(String url) { return requestBuilder("PUT", url); } /** * Prepare an HTTP client DELETE request. * @param url A well formed URL. * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareDelete(String url) { return requestBuilder("DELETE", url); } /** * Construct a {@link RequestBuilder} using a {@link Request} * @param request a {@link Request} * @return {@link RequestBuilder} */ public BoundRequestBuilder prepareRequest(Request request) { return requestBuilder(request); } /** * Execute an HTTP request. * @param request {@link Request} * @param handler an instance of {@link AsyncHandler} * @param <T> Type of the value that will be returned by the associated {@link java.util.concurrent.Future} * @return a {@link Future} of type T * @throws IOException */ public <T> Future<T> executeRequest(Request request, AsyncHandler<T> handler) throws IOException { return httpProvider.execute(request, handler); } /** * Execute an HTTP request. * @param request {@link Request} * @return a {@link Future} of type Response * @throws IOException */ public Future<Response> executeRequest(Request request) throws IOException { return httpProvider.execute(request, new AsyncCompletionHandlerBase()); } @SuppressWarnings("unchecked") private final static AsyncHttpProvider<?> loadDefaultProvider(String className, AsyncHttpClientConfig config){ try { Class<AsyncHttpProvider<?>> providerClass = (Class<AsyncHttpProvider<?>>) Thread.currentThread() .getContextClassLoader().loadClass(className); return (AsyncHttpProvider<?>) providerClass.getDeclaredConstructor( new Class[]{AsyncHttpClientConfig.class}).newInstance(new Object[]{config}); } catch (Throwable t){ if (logger.isDebugEnabled()) { logger.debug(String.format("Default provider not found %s. Using the %s", DEFAULT_PROVIDER, JDKAsyncHttpProvider.class.getName())); } return new JDKAsyncHttpProvider(config); } } protected BoundRequestBuilder requestBuilder(String reqType, String url) { return new BoundRequestBuilder(reqType).setUrl(url).setSignatureCalculator(signatureCalculator); } protected BoundRequestBuilder requestBuilder(Request prototype) { return new BoundRequestBuilder(prototype).setSignatureCalculator(signatureCalculator); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.tagplugins.jstl.core; import java.io.IOException; import java.io.Reader; import javax.servlet.jsp.JspWriter; import org.apache.jasper.compiler.tagplugin.TagPlugin; import org.apache.jasper.compiler.tagplugin.TagPluginContext; import org.apache.jasper.tagplugins.jstl.Util; public final class Out implements TagPlugin { @Override public void doTag(TagPluginContext ctxt) { // these two data member are to indicate // whether the corresponding attribute is specified boolean hasDefault = false, hasEscapeXml = false; hasDefault = ctxt.isAttributeSpecified("default"); hasEscapeXml = ctxt.isAttributeSpecified("escapeXml"); // strValName, strEscapeXmlName & strDefName are two variables' name // standing for value, escapeXml and default attribute String strObjectName = ctxt.getTemporaryVariableName(); String strValName = ctxt.getTemporaryVariableName(); String strDefName = ctxt.getTemporaryVariableName(); String strEscapeXmlName = ctxt.getTemporaryVariableName(); String strSkipBodyName = ctxt.getTemporaryVariableName(); // according to the tag file, the value attribute is mandatory. ctxt.generateImport("java.io.Reader"); ctxt.generateJavaSource("Object " + strObjectName + "="); ctxt.generateAttribute("value"); ctxt.generateJavaSource(";"); ctxt.generateJavaSource("String " + strValName + "=null;"); ctxt.generateJavaSource("if(!(" + strObjectName + " instanceof Reader) && " + strObjectName + " != null){"); ctxt.generateJavaSource(strValName + " = " + strObjectName + ".toString();"); ctxt.generateJavaSource("}"); // initiate the strDefName with null. // if the default has been specified, then assign the value to it; ctxt.generateJavaSource("String " + strDefName + " = null;"); if (hasDefault) { ctxt.generateJavaSource("if("); ctxt.generateAttribute("default"); ctxt.generateJavaSource(" != null){"); ctxt.generateJavaSource(strDefName + " = ("); ctxt.generateAttribute("default"); ctxt.generateJavaSource(").toString();"); ctxt.generateJavaSource("}"); } // initiate the strEscapeXmlName with true; // if the escapeXml is specified, assign the value to it; ctxt.generateJavaSource("boolean " + strEscapeXmlName + " = true;"); if (hasEscapeXml) { ctxt.generateJavaSource(strEscapeXmlName + " = "); ctxt.generateAttribute("escapeXml"); ctxt.generateJavaSource(";"); } // main part. ctxt.generateJavaSource( "boolean " + strSkipBodyName + " = " + "org.apache.jasper.tagplugins.jstl.core.Out.output(out, " + strObjectName + ", " + strValName + ", " + strDefName + ", " + strEscapeXmlName + ");"); ctxt.generateJavaSource("if(!" + strSkipBodyName + ") {"); ctxt.generateBody(); ctxt.generateJavaSource("}"); } public static boolean output(JspWriter out, Object input, String value, String defaultValue, boolean escapeXml) throws IOException { if (input instanceof Reader) { char[] buffer = new char[8096]; int read = 0; while (read != -1) { read = ((Reader) input).read(buffer); if (read != -1) { if (escapeXml) { String escaped = Util.escapeXml(buffer, read); if (escaped == null) { out.write(buffer, 0, read); } else { out.print(escaped); } } else { out.write(buffer, 0, read); } } } return true; } else { String v = value != null ? value : defaultValue; if (v != null) { if (escapeXml) { v = Util.escapeXml(v); } out.write(v); return true; } else { return false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.api.jms.management; import java.util.Map; import javax.management.MBeanOperationInfo; import org.apache.activemq.artemis.api.core.management.Operation; import org.apache.activemq.artemis.api.core.management.Parameter; /** * A TopicControl is used to manage a JMS Topic. */ public interface TopicControl extends DestinationControl { /** * Returns the number of (durable and non-durable) subscribers for this topic. */ int getSubscriptionCount(); /** * Returns the number of <em>durable</em> subscribers for this topic. */ int getDurableSubscriptionCount(); /** * Returns the number of <em>non-durable</em> subscribers for this topic. */ int getNonDurableSubscriptionCount(); /** * Returns the number of messages for all <em>durable</em> subscribers for this topic. */ int getDurableMessageCount(); /** * Returns the number of messages for all <em>non-durable</em> subscribers for this topic. */ int getNonDurableMessageCount(); /** * Returns the Registry bindings associated to this connection factory. */ @Operation(desc = "Returns the list of Registry bindings associated") String[] getRegistryBindings(); /** * Add the Registry binding to this destination */ @Operation(desc = "Adds the queue to another Registry binding") void addBinding(@Parameter(name = "binding", desc = "the name of the binding for Registry") String binding) throws Exception; // Operations ---------------------------------------------------- /** * Lists all the subscriptions for this topic (both durable and non-durable). */ @Operation(desc = "List all subscriptions") Object[] listAllSubscriptions() throws Exception; /** * Lists all the subscriptions for this topic (both durable and non-durable) using JSON serialization. * <br> * Java objects can be recreated from JSON serialization using {@link SubscriptionInfo#from(String)}. */ @Operation(desc = "List all subscriptions") String listAllSubscriptionsAsJSON() throws Exception; /** * Lists all the <em>durable</em> subscriptions for this topic. */ @Operation(desc = "List only the durable subscriptions") Object[] listDurableSubscriptions() throws Exception; /** * Lists all the <em>durable</em> subscriptions using JSON serialization. * <br> * Java objects can be recreated from JSON serialization using {@link SubscriptionInfo#from(String)}. */ @Operation(desc = "List only the durable subscriptions") String listDurableSubscriptionsAsJSON() throws Exception; /** * Lists all the <em>non-durable</em> subscriptions for this topic. */ @Operation(desc = "List only the non durable subscriptions") Object[] listNonDurableSubscriptions() throws Exception; /** * Lists all the <em>non-durable</em> subscriptions using JSON serialization. * <br> * Java objects can be recreated from JSON serialization using {@link SubscriptionInfo#from(String)}. */ @Operation(desc = "List only the non durable subscriptions") String listNonDurableSubscriptionsAsJSON() throws Exception; /** * Lists all the messages in this queue matching the specified queue representing the subscription. * <br> * 1 Map represents 1 message, keys are the message's properties and headers, values are the corresponding values. */ @Operation(desc = "List all the message for the given subscription") Map<String, Object>[] listMessagesForSubscription(@Parameter(name = "queueName", desc = "the name of the queue representing a subscription") String queueName) throws Exception; /** * Lists all the messages in this queue matching the specified queue representing the subscription using JSON serialization. */ @Operation(desc = "List all the message for the given subscription") String listMessagesForSubscriptionAsJSON(@Parameter(name = "queueName", desc = "the name of the queue representing a subscription") String queueName) throws Exception; /** * Counts the number of messages in the subscription specified by the specified client ID and subscription name. Only messages matching the filter will be counted. * <br> * Using {@code null} or an empty filter will count <em>all</em> messages from this queue. */ @Operation(desc = "Count the number of messages matching the filter for the given subscription") int countMessagesForSubscription(@Parameter(name = "clientID", desc = "the client ID") String clientID, @Parameter(name = "subscriptionName", desc = "the name of the durable subscription") String subscriptionName, @Parameter(name = "filter", desc = "a JMS filter (can be empty)") String filter) throws Exception; /** * Drops the subscription specified by the specified client ID and subscription name. */ @Operation(desc = "Drop a durable subscription", impact = MBeanOperationInfo.ACTION) void dropDurableSubscription(@Parameter(name = "clientID", desc = "the client ID") String clientID, @Parameter(name = "subscriptionName", desc = "the name of the durable subscription") String subscriptionName) throws Exception; /** * Drops all subscriptions. */ @Operation(desc = "Drop all subscriptions from this topic", impact = MBeanOperationInfo.ACTION) void dropAllSubscriptions() throws Exception; }
package com.example.workerservice.service.api.user; import com.example.workerservice.service.command.user.updatepwd.UpdateUserPwdCommand; /** * 接口 - 修改用户密码 */ public interface IUpdateUserPwdCommandHandler { void action(UpdateUserPwdCommand command); /** * 自定义业务异常 - 验证码错误 **/ class IncorrectVerifyCodeException extends RuntimeException { public IncorrectVerifyCodeException() { super("输入的验证码错误"); } } /** * 自定义业务异常 - 验证码错误 **/ class InvalidVerifyCodeException extends RuntimeException { public InvalidVerifyCodeException() { super("验证码不存在,请重新获取"); } } /** * 自定义业务异常 - 用户未发现 **/ class UserNotFoundException extends RuntimeException { public UserNotFoundException() { super("账号或密码错误"); } } }
package com.iskinfor.servicedata.pojo; /** * 获奖者 * @author Administrator * */ public class Winner { private String userName;//获奖者姓名 private String awardDate;//获奖日期 private String awardCourse;//获奖课程 private String winnerInfor;//获奖情况 private int pags;//总条数 public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAwardDate() { return awardDate; } public void setAwardDate(String awardDate) { this.awardDate = awardDate; } public String getAwardCourse() { return awardCourse; } public void setAwardCourse(String awardCourse) { this.awardCourse = awardCourse; } public String getWinnerInfor() { return winnerInfor; } public void setWinnerInfor(String winnerInfor) { this.winnerInfor = winnerInfor; } public int getPags() { return pags; } public void setPags(int pags) { this.pags = pags; } }
package com_peszke.controller; public enum EmailLoginResult { SUCCESS, FAILED_BY_CREDENTIALS, FAILED_BY_NETWORK, FAILED_BY_UNEXPECTED_ERROR; }
package io.deephaven.db.v2.tuples.generated; import io.deephaven.datastructures.util.SmartKey; import io.deephaven.db.util.tuples.generated.IntDoubleObjectTuple; import io.deephaven.db.v2.sources.ColumnSource; import io.deephaven.db.v2.sources.WritableSource; import io.deephaven.db.v2.sources.chunk.Attributes; import io.deephaven.db.v2.sources.chunk.Chunk; import io.deephaven.db.v2.sources.chunk.DoubleChunk; import io.deephaven.db.v2.sources.chunk.IntChunk; import io.deephaven.db.v2.sources.chunk.ObjectChunk; import io.deephaven.db.v2.sources.chunk.WritableChunk; import io.deephaven.db.v2.sources.chunk.WritableObjectChunk; import io.deephaven.db.v2.tuples.AbstractTupleSource; import io.deephaven.db.v2.tuples.ThreeColumnTupleSourceFactory; import io.deephaven.db.v2.tuples.TupleSource; import io.deephaven.util.type.TypeUtils; import org.jetbrains.annotations.NotNull; /** * <p>{@link TupleSource} that produces key column values from {@link ColumnSource} types Integer, Double, and Object. * <p>Generated by {@link io.deephaven.db.v2.tuples.TupleSourceCodeGenerator}. */ @SuppressWarnings({"unused", "WeakerAccess"}) public class IntegerDoubleObjectColumnTupleSource extends AbstractTupleSource<IntDoubleObjectTuple> { /** {@link ThreeColumnTupleSourceFactory} instance to create instances of {@link IntegerDoubleObjectColumnTupleSource}. **/ public static final ThreeColumnTupleSourceFactory<IntDoubleObjectTuple, Integer, Double, Object> FACTORY = new Factory(); private final ColumnSource<Integer> columnSource1; private final ColumnSource<Double> columnSource2; private final ColumnSource<Object> columnSource3; public IntegerDoubleObjectColumnTupleSource( @NotNull final ColumnSource<Integer> columnSource1, @NotNull final ColumnSource<Double> columnSource2, @NotNull final ColumnSource<Object> columnSource3 ) { super(columnSource1, columnSource2, columnSource3); this.columnSource1 = columnSource1; this.columnSource2 = columnSource2; this.columnSource3 = columnSource3; } @Override public final IntDoubleObjectTuple createTuple(final long indexKey) { return new IntDoubleObjectTuple( columnSource1.getInt(indexKey), columnSource2.getDouble(indexKey), columnSource3.get(indexKey) ); } @Override public final IntDoubleObjectTuple createPreviousTuple(final long indexKey) { return new IntDoubleObjectTuple( columnSource1.getPrevInt(indexKey), columnSource2.getPrevDouble(indexKey), columnSource3.getPrev(indexKey) ); } @Override public final IntDoubleObjectTuple createTupleFromValues(@NotNull final Object... values) { return new IntDoubleObjectTuple( TypeUtils.unbox((Integer)values[0]), TypeUtils.unbox((Double)values[1]), values[2] ); } @Override public final IntDoubleObjectTuple createTupleFromReinterpretedValues(@NotNull final Object... values) { return new IntDoubleObjectTuple( TypeUtils.unbox((Integer)values[0]), TypeUtils.unbox((Double)values[1]), values[2] ); } @SuppressWarnings("unchecked") @Override public final <ELEMENT_TYPE> void exportElement(@NotNull final IntDoubleObjectTuple tuple, final int elementIndex, @NotNull final WritableSource<ELEMENT_TYPE> writableSource, final long destinationIndexKey) { if (elementIndex == 0) { writableSource.set(destinationIndexKey, tuple.getFirstElement()); return; } if (elementIndex == 1) { writableSource.set(destinationIndexKey, tuple.getSecondElement()); return; } if (elementIndex == 2) { writableSource.set(destinationIndexKey, (ELEMENT_TYPE) tuple.getThirdElement()); return; } throw new IndexOutOfBoundsException("Invalid element index " + elementIndex + " for export"); } @Override public final Object exportToExternalKey(@NotNull final IntDoubleObjectTuple tuple) { return new SmartKey( TypeUtils.box(tuple.getFirstElement()), TypeUtils.box(tuple.getSecondElement()), tuple.getThirdElement() ); } @Override public final Object exportElement(@NotNull final IntDoubleObjectTuple tuple, int elementIndex) { if (elementIndex == 0) { return TypeUtils.box(tuple.getFirstElement()); } if (elementIndex == 1) { return TypeUtils.box(tuple.getSecondElement()); } if (elementIndex == 2) { return tuple.getThirdElement(); } throw new IllegalArgumentException("Bad elementIndex for 3 element tuple: " + elementIndex); } @Override public final Object exportElementReinterpreted(@NotNull final IntDoubleObjectTuple tuple, int elementIndex) { if (elementIndex == 0) { return TypeUtils.box(tuple.getFirstElement()); } if (elementIndex == 1) { return TypeUtils.box(tuple.getSecondElement()); } if (elementIndex == 2) { return tuple.getThirdElement(); } throw new IllegalArgumentException("Bad elementIndex for 3 element tuple: " + elementIndex); } @Override protected void convertChunks(@NotNull WritableChunk<? super Attributes.Values> destination, int chunkSize, Chunk<Attributes.Values> [] chunks) { WritableObjectChunk<IntDoubleObjectTuple, ? super Attributes.Values> destinationObjectChunk = destination.asWritableObjectChunk(); IntChunk<Attributes.Values> chunk1 = chunks[0].asIntChunk(); DoubleChunk<Attributes.Values> chunk2 = chunks[1].asDoubleChunk(); ObjectChunk<Object, Attributes.Values> chunk3 = chunks[2].asObjectChunk(); for (int ii = 0; ii < chunkSize; ++ii) { destinationObjectChunk.set(ii, new IntDoubleObjectTuple(chunk1.get(ii), chunk2.get(ii), chunk3.get(ii))); } destinationObjectChunk.setSize(chunkSize); } /** {@link ThreeColumnTupleSourceFactory} for instances of {@link IntegerDoubleObjectColumnTupleSource}. **/ private static final class Factory implements ThreeColumnTupleSourceFactory<IntDoubleObjectTuple, Integer, Double, Object> { private Factory() { } @Override public TupleSource<IntDoubleObjectTuple> create( @NotNull final ColumnSource<Integer> columnSource1, @NotNull final ColumnSource<Double> columnSource2, @NotNull final ColumnSource<Object> columnSource3 ) { return new IntegerDoubleObjectColumnTupleSource( columnSource1, columnSource2, columnSource3 ); } } }
/** * Copyright 2012 Akiban Technologies, Inc. * * 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 com.persistit; import org.junit.Test; import static org.junit.Assert.assertTrue; public class Bug992801Test extends PersistitUnitTestCase { /* * https://bugs.launchpad.net/akiban-persistit/+bug/992801 * * A transaction creates an table index and commits. Subsequently many * threads read the index. Because there are no other update transactions * the TransactionStatus for the index creation remains present in the * TransactionIndex, and therefore the concurrent reader threads are slowed * by contention on the bucket lock in getStatus. * * Fixing this could improve performance in some scenarios. For example, * customer creates a new index and then starts a bunch of concurrent query * threads. Note that ongoing replication clears the condition relatively * quickly, so this is a condition that requires little or no update * activity subsequent to index creation. The bug is exploited particularly * on indexes because query threads traverse the index and repeatedly see * MVVs with the same transaction's start timestamp. */ @Test public void testFloorRises() throws Exception { final Transaction txn = _persistit.getTransaction(); final Exchange ex = _persistit.getExchange("persistit", "Bug992801Test", true); txn.begin(); final long tsv = txn.getStartTimestamp(); for (int i = 1; i < 1000; i++) { ex.getValue().put(RED_FOX + i); ex.to(i).store(); } txn.commit(); txn.end(); long whenStatusCleared = Long.MAX_VALUE; final long start = System.currentTimeMillis(); while (System.currentTimeMillis() < start + 5000) { final TransactionStatus status = _persistit.getTransactionIndex().getStatus(tsv); if (status == null) { whenStatusCleared = System.currentTimeMillis(); break; } Thread.sleep(10); } assertTrue(String.format("Should have cleared within 1000ms, actual=%,d", whenStatusCleared - start), whenStatusCleared - start < 1000); } }
package com.kaqi.niuniu.ireader.utils.media; import android.content.Context; import android.os.Bundle; import android.support.v4.content.CursorLoader; /** * Created by newbiechen on 2018/1/14. */ public class LoaderCreator { public static final int ALL_BOOK_FILE = 1; public static CursorLoader create(Context context, int id, Bundle bundle) { LocalFileLoader loader = null; switch (id){ case ALL_BOOK_FILE: loader = new LocalFileLoader(context); break; default: loader = null; break; } if (loader != null) { return loader; } throw new IllegalArgumentException("The id of Loader is invalid!"); } }
package com.pskwierc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() // .formLogin() // .loginPage("/login") // .permitAll() // .and() // .logout() // .permitAll(); .formLogin() .loginPage("/login") .permitAll() .defaultSuccessUrl("/hello") .failureUrl("/login?error") .and() .logout() //.logoutSuccessUrl("/login.html?logout=true") .permitAll(); } @Bean @Override public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
package mage.cards.r; import mage.MageInt; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.common.delayed.AtTheBeginOfNextEndStepDelayedTriggeredAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.ReturnToBattlefieldUnderOwnerControlTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.common.FilterControlledCreaturePermanent; import mage.game.Game; import mage.game.permanent.Permanent; import mage.target.common.TargetCreaturePermanent; import mage.target.targetpointer.FixedTarget; import java.util.UUID; /** * @author NinthWorld */ public final class RangeTrooper extends CardImpl { private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("Trooper creatures"); static { filter.add(SubType.TROOPER.getPredicate()); } public RangeTrooper(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.TROOPER); this.power = new MageInt(2); this.toughness = new MageInt(2); // Trooper creatures you control have "When this creature enters that battlefield, you may exile target creature. Return that creature to the battlefield at the beginning of the next end step." Ability ability = new EntersBattlefieldTriggeredAbility(new RangeTrooperEffect(), true, false); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new GainAbilityControlledEffect(ability, Duration.WhileOnBattlefield, filter, false))); } public RangeTrooper(final RangeTrooper card) { super(card); } @Override public RangeTrooper copy() { return new RangeTrooper(this); } } class RangeTrooperEffect extends OneShotEffect { public RangeTrooperEffect() { super(Outcome.Detriment); staticText = "exile target creature. Return that creature to the battlefield at the beginning of the next end step"; } public RangeTrooperEffect(final RangeTrooperEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Permanent permanent = game.getPermanent(source.getFirstTarget()); MageObject sourceObject = game.getObject(source.getSourceId()); if (permanent != null && sourceObject != null) { if (permanent.moveToExile(source.getSourceId(), sourceObject.getIdName(), source, game)) { Effect effect = new ReturnToBattlefieldUnderOwnerControlTargetEffect(false, false); effect.setText("Return that card to the battlefield under its owner's control at the beginning of the next end step"); effect.setTargetPointer(new FixedTarget(source.getFirstTarget(), game)); game.addDelayedTriggeredAbility(new AtTheBeginOfNextEndStepDelayedTriggeredAbility(effect), source); return true; } } return false; } @Override public RangeTrooperEffect copy() { return new RangeTrooperEffect(this); } }
package ru.otus.demo; import org.hibernate.cfg.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.otus.core.repository.DataTemplateHibernate; import ru.otus.core.repository.HibernateUtils; import ru.otus.core.sessionmanager.TransactionManagerHibernate; import ru.otus.crm.dbmigrations.MigrationsExecutorFlyway; import ru.otus.crm.model.Address; import ru.otus.crm.model.Client; import ru.otus.crm.model.Phone; import ru.otus.crm.service.DbServiceClientImpl; import java.util.ArrayList; public class DbServiceDemo { private static final Logger log = LoggerFactory.getLogger(DbServiceDemo.class); public static final String HIBERNATE_CFG_FILE = "hibernate.cfg.xml"; public static void main(String[] args) { var configuration = new Configuration().configure(HIBERNATE_CFG_FILE); var dbUrl = configuration.getProperty("hibernate.connection.url"); var dbUserName = configuration.getProperty("hibernate.connection.username"); var dbPassword = configuration.getProperty("hibernate.connection.password"); new MigrationsExecutorFlyway(dbUrl, dbUserName, dbPassword).executeMigrations(); var sessionFactory = HibernateUtils.buildSessionFactory(configuration, Client.class, Address.class, Phone.class); var transactionManager = new TransactionManagerHibernate(sessionFactory); /// var clientTemplate = new DataTemplateHibernate<>(Client.class); /// var dbServiceClient = new DbServiceClientImpl(transactionManager, clientTemplate); var client1 = new Client("dbServiceFirst"); var addres1 = new Address("Street1"); addres1.setClient(client1); client1.setAddress(addres1); var phones = new ArrayList<Phone>(); for (int i = 1; i <= 7; i++) { phones.add(new Phone("55555" + i, client1)); } client1.setPhones(phones); dbServiceClient.saveClient(client1); var clientSecond = dbServiceClient.saveClient(new Client("dbServiceSecond")); var clientSecondSelected = dbServiceClient.getClient(clientSecond.getId()) .orElseThrow(() -> new RuntimeException("Client not found, id:" + clientSecond.getId())); log.info("clientSecondSelected:{}", clientSecondSelected); /// dbServiceClient.saveClient(new Client(clientSecondSelected.getId(), "dbServiceSecondUpdated")); var clientUpdated = dbServiceClient.getClient(clientSecondSelected.getId()) .orElseThrow(() -> new RuntimeException("Client not found, id:" + clientSecondSelected.getId())); log.info("clientUpdated:{}", clientUpdated); log.info("All clients"); dbServiceClient.findAll().forEach(client -> log.info("client:{}", client)); } }
package es.cj.controller; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import es.cj.bean.Conexion; import es.cj.bean.Usuario; import es.cj.dao.UsuarioDAO; import es.cj.dao.UsuarioDAOImpl; /** * Servlet implementation class ActualizarUsuarios */ public class ActualizarUsuarios extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ActualizarUsuarios() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String login = request.getParameter("login"); String nombre = request.getParameter("nombre"); String apellidos = request.getParameter("apellidos"); String email = request.getParameter("email"); String passwordNueva = request.getParameter("passwordNueva"); int idUsuario = Integer.parseInt(request.getParameter("idUsuario")); int tipo = Integer.parseInt(request.getParameter("tipo")); String password = request.getParameter("password"); String loginAdmin = request.getParameter("loginAdmin"); int idAdmin = Integer.parseInt(request.getParameter("idAdmin")); ServletContext sc = getServletContext(); String usu = sc.getInitParameter("usuario"); String pass = sc.getInitParameter("password"); String driver = sc.getInitParameter("driver"); String bd = sc.getInitParameter("database"); Conexion con = new Conexion(usu, pass, driver, bd); Usuario usuario = new Usuario(idUsuario, login, nombre, apellidos, passwordNueva, email, tipo); UsuarioDAO uDAO = new UsuarioDAOImpl(); Usuario usuarioComp = uDAO.comprobarUsuario(loginAdmin, password, con); if (usuarioComp != null) { int filas = uDAO.actualizarUsuario(con, usuario); if (filas == 1) { HttpSession session = request.getSession(); session.removeAttribute("usuarioWeb"); session.invalidate(); HttpSession sesion = request.getSession(); Usuario u = uDAO.listarXId(con, idAdmin); //Pongo al usuario en la sesion sesion.setAttribute("usuarioWeb", u); response.sendRedirect("jsp/administracionUsuarios.jsp?mensaje=Actualizado correctamente"); } else { response.sendRedirect("jsp/administracionUsuarios.jsp?mensaje=Error al actualizar"); } } else { response.sendRedirect("jsp/administracionUsuarios.jsp?mensaje=Contraseña incorrecta"); } } }
package com.alibaba.android.arouter.demo.kotlin; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.alibaba.android.arouter.facade.annotation.Route; @Route(path = "/kotlin/java") public class TestNormalActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_normal); } }
package com.hackmann.polarity.pairing; import com.hackmann.polarity.user.User; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; @Service @EnableScheduling public class PairingService { private HashMap<String, Queue> queues = new HashMap<>(); public PairingService() { } public Queue makeNewQueue(String topicName) { Queue queue = new Queue(topicName); this.queues.put(topicName, queue); return queue; } public Queue getQueue(String topicName) { Queue queue = this.queues.get(topicName); return queue != null ? queue : this.makeNewQueue(topicName); } public void removeFromQueues(User user) { this.queues.forEach((k, queue) -> { queue.removeUserFromQueue(user); }); } @Scheduled(fixedDelay = 1000) public void updateQueues() { this.queues.forEach((k, queue) -> { queue.updateQueue(); }); } }
package org.edx.mobile.social; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import org.edx.mobile.R; import org.edx.mobile.exception.LoginErrorMessage; import org.edx.mobile.exception.LoginException; import org.edx.mobile.logger.Logger; import org.edx.mobile.model.api.AuthResponse; import org.edx.mobile.model.api.ProfileModel; import org.edx.mobile.module.prefs.PrefManager; import org.edx.mobile.services.ServiceManager; import org.edx.mobile.social.facebook.FacebookProvider; import org.edx.mobile.social.google.GoogleOauth2; import org.edx.mobile.social.google.GoogleProvider; import org.edx.mobile.task.Task; import org.edx.mobile.util.Config; import org.edx.mobile.util.NetworkUtil; import org.edx.mobile.util.ResourceUtil; import org.edx.mobile.view.ICommonUI; import java.util.HashMap; /** * Code refactored from Login Activity, for the logic of login to social site are the same * for both login and registration. * * Created by hanning on 3/11/15. */ public class SocialLoginDelegate { protected final Logger logger = new Logger(getClass().getName()); private Activity activity; private MobileLoginCallback callback; private SocialUserInfoCallback userInfoCallback; private ISocial google, facebook; private String userEmail; private ISocial.Callback googleCallback = new ISocial.Callback() { @Override public void onLogin(String accessToken) { logger.debug("Google logged in; token= " + accessToken); onSocialLoginSuccess(accessToken, PrefManager.Value.BACKEND_GOOGLE); } }; private ISocial.Callback facebookCallback = new ISocial.Callback() { @Override public void onLogin(String accessToken) { logger.debug("Facebook logged in; token= " + accessToken); onSocialLoginSuccess(accessToken, PrefManager.Value.BACKEND_FACEBOOK); } }; public SocialLoginDelegate(Activity activity, Bundle savedInstanceState, MobileLoginCallback callback, Config config){ this.activity = activity; this.callback = callback; google = SocialFactory.getInstance(activity, SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_GOOGLE, config); google.setCallback(googleCallback); facebook = SocialFactory.getInstance(activity, SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK, config); facebook.setCallback(facebookCallback); google.onActivityCreated(activity, savedInstanceState); facebook.onActivityCreated(activity, savedInstanceState); } public void init(){ } public void onActivityDestroyed(){ google.onActivityDestroyed(activity); facebook.onActivityDestroyed(activity); } public void onActivitySaveInstanceState(Bundle outState){ google.onActivitySaveInstanceState(activity, outState); facebook.onActivitySaveInstanceState(activity, outState); } public void onActivityStarted(){ google.onActivityStarted(activity); facebook.onActivityStarted(activity); } public void onActivityResult(int requestCode, int resultCode, Intent data) { google.onActivityResult(requestCode, resultCode, data); facebook.onActivityResult(requestCode, resultCode, data); } public void onActivityStopped() { google.onActivityStopped(activity); facebook.onActivityStopped(activity); } public void socialLogin(SocialFactory.SOCIAL_SOURCE_TYPE socialType){ if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK ) facebook.login(); else if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_GOOGLE ) google.login(); } public void socialLogout(SocialFactory.SOCIAL_SOURCE_TYPE socialType){ if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK ) facebook.logout(); else if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_GOOGLE ) google.logout(); } /** * called with you to use social login * @param accessToken * @param backend */ public void onSocialLoginSuccess(String accessToken, String backend) { PrefManager pref = new PrefManager(activity, PrefManager.Pref.LOGIN); pref.put(PrefManager.Key.AUTH_TOKEN_SOCIAL, accessToken); pref.put(PrefManager.Key.AUTH_TOKEN_BACKEND, backend); //for debug purpose. // Exception ex = new RuntimeException( ); // callback.onUserLoginFailure(ex, accessToken, backend); Task<?> task = new ProfileTask(activity,accessToken, backend); callback.onSocialLoginSuccess(accessToken, backend, task); task.execute(); } public void setUserEmail(String email){ this.userEmail = email; } public String getUserEmail(){ return this.userEmail; } public void getUserInfo(SocialFactory.SOCIAL_SOURCE_TYPE socialType, String accessToken, final SocialUserInfoCallback userInfoCallback){ SocialProvider socialProvider = null; if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK ) { socialProvider = new FacebookProvider(); } else if ( socialType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_GOOGLE ) { socialProvider = new GoogleProvider((GoogleOauth2) google); } if ( socialProvider != null ) { socialProvider.getUserInfo(activity, socialType, accessToken, userInfoCallback); } } private class ProfileTask extends Task<ProfileModel> { private String accessToken; private String backend; public ProfileTask(Context context, String accessToken, String backend) { super(context); this.accessToken = accessToken; this.backend = backend; } @Override public void onSuccess(ProfileModel result) { if (result != null) { try { if (result.email == null) { // handle this error, show error message LoginErrorMessage errorMsg = new LoginErrorMessage( context.getString(R.string.login_error), context.getString(R.string.login_failed)); throw new LoginException(errorMsg); } callback.onUserLoginSuccess(result); } catch (LoginException ex) { logger.error(ex); handle(ex); } } } @Override public void onException(Exception ex) { callback.onUserLoginFailure(ex, this.accessToken, this.backend); } @Override public ProfileModel call( ) { try { ServiceManager api = environment.getServiceManager(); // do SOCIAL LOGIN first AuthResponse social = null; HashMap<String, CharSequence> descParams = new HashMap<>(); String platformName = environment.getConfig().getPlatformName(); descParams.put("platform_name", environment.getConfig().getPlatformName()); descParams.put("platform_destination", environment.getConfig().getPlatformDestinationName()); if (backend.equalsIgnoreCase(PrefManager.Value.BACKEND_FACEBOOK)) { social = api.loginByFacebook(accessToken); if ( social.error != null && social.error.equals("401") ) { CharSequence title = ResourceUtil.getFormattedString(context.getResources(), R.string.error_account_not_linked_title_fb, descParams); CharSequence desc = ResourceUtil.getFormattedString(context.getResources(), R.string.error_account_not_linked_desc_fb, descParams); throw new LoginException(new LoginErrorMessage(title.toString(), desc.toString())); } } else if (backend.equalsIgnoreCase(PrefManager.Value.BACKEND_GOOGLE)) { social = api.loginByGoogle(accessToken); if ( social.error != null && social.error.equals("401") ) { CharSequence title = ResourceUtil.getFormattedString(context.getResources(), R.string.error_account_not_linked_title_google, descParams); CharSequence desc = ResourceUtil.getFormattedString(context.getResources(), R.string.error_account_not_linked_desc_google, descParams); throw new LoginException(new LoginErrorMessage(title.toString(), desc.toString())); } } if (social.isSuccess()) { // we got a valid accessToken so profile can be fetched ProfileModel profile = api.getProfile(); if (profile.email != null) { // we got valid profile information return profile; } } throw new LoginException(new LoginErrorMessage( context.getString(R.string.login_error), context.getString(R.string.login_failed))); } catch (Exception e) { logger.error(e); handle(e); } return null; } } public SocialButtonClickHandler createSocialButtonClickHandler(SocialFactory.SOCIAL_SOURCE_TYPE socialType){ return new SocialButtonClickHandler(socialType); } public class SocialButtonClickHandler implements View.OnClickListener{ private SocialFactory.SOCIAL_SOURCE_TYPE socialType; private SocialButtonClickHandler(SocialFactory.SOCIAL_SOURCE_TYPE socialType){ this.socialType = socialType; } @Override public void onClick(View v) { if (!NetworkUtil.isConnected(activity)) { callback.showErrorMessage(activity.getString(R.string.no_connectivity), activity.getString(R.string.network_not_connected)); } else { Task<Void> logout = new Task<Void>(activity) { @Override public Void call( ) { try { socialLogout(socialType); } catch(Exception ex) { // no need to handle this error logger.error(ex); } return null; } @Override public void onSuccess(Void result) { socialLogin(socialType); } @Override public void onException(Exception ex) { logger.error(ex); if ( activity instanceof ICommonUI) ((ICommonUI)activity).tryToSetUIInteraction(true); } }; if ( activity instanceof ICommonUI) ((ICommonUI)activity).tryToSetUIInteraction(false); logout.execute(); } } } public interface MobileLoginCallback { void onSocialLoginSuccess(String accessToken, String backend, Task task); void onUserLoginFailure(Exception ex, String accessToken, String backend); void onUserLoginSuccess(ProfileModel profile) throws LoginException; boolean showErrorMessage(String header, String message); } public interface SocialUserInfoCallback{ void setSocialUserInfo(String email, String name); } }
/* * Copyright 2016 Andreas Fester * * 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 afester.javafx.tools; import javafx.event.Event; import javafx.event.EventType; import javafx.scene.input.KeyCode; public class KeyStateEvent extends Event { private static final long serialVersionUID = -973185130826008148L; private static final EventType<KeyStateEvent> EVENT_TYPE = new EventType<>("KEY_CHANGE_EVENT"); private KeyCode key; public KeyStateEvent(KeyCode activeKey) { super(null, null, EVENT_TYPE); this.key = activeKey; } public KeyCode getKeyCode() { return key; } @Override public String toString() { return "KeyChangeEvent[" + key + "]"; } }
package com.beginningselenium.examples.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class AgeCalculatorPage { //WebElements private WebElement dayOfBirth = null; private WebElement monthOfBirth = null; private WebElement yearOfBirth = null; private WebElement age = null; private WebElement zodiacSign = null; private WebElement calculate = null; ///WebDriver private WebDriver driver; private String url = "https://trainingbypackt.github.io/Beginning-Selenium/lesson_9/activity_9_A-1.html"; //Class Constructor public AgeCalculatorPage(WebDriver webDriver) { driver = webDriver; } //Methods to open and close the WebDriver public void open() { this.driver.get(url); } public void close() { this.driver.quit(); } //Method to execute the test public void calculate(String day, String month, String year) { getDayOfBirth().sendKeys(day); getMonthOfBirth().sendKeys(month); getYearOfBirth().sendKeys(year); getCalculate().click(); } //Methods to read values from required WebElements public String getAge() { age = driver.findElement(By.id("age")); return age.getText(); } public String getZodiacSign() { zodiacSign = driver.findElement(By.id("zodiacSign")); return zodiacSign.getText(); } public WebElement getDayOfBirth() { dayOfBirth = driver.findElement(By.id("dayOfBirth")); return dayOfBirth; } public WebElement getMonthOfBirth() { monthOfBirth = driver.findElement(By.id("monthOfBirth")); return monthOfBirth; } public WebElement getYearOfBirth() { yearOfBirth = driver.findElement(By.id("yearOfBirth")); return yearOfBirth; } public WebElement getCalculate() { calculate = driver.findElement(By.id("calculate")); return calculate; } }
package com.dmd.weixin.qy.jsapi; import com.fasterxml.jackson.annotation.JsonProperty; import com.dmd.weixin.common.WxClient; import com.dmd.weixin.common.decrypt.AesException; import com.dmd.weixin.common.decrypt.SHA1; import com.dmd.weixin.common.exception.WxRuntimeException; import com.dmd.weixin.common.jsapi.JsAPISignature; import com.dmd.weixin.common.util.JsonMapper; import com.dmd.weixin.common.util.RandomStringGenerator; import com.dmd.weixin.qy.QyWxClientFactory; import com.dmd.weixin.qy.base.CorpSetting; import com.dmd.weixin.qy.base.WxEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 微信JSAPI * Created by exizhai on 1/27/2016. */ public class JsAPIs { private static Logger logger = LoggerFactory.getLogger(JsAPIs.class); private APITicket jsAPITicket; private APITicket jsAPIGroupTicket; private WxClient wxClient; public static JsAPIs defaultJsAPIs() { return with(CorpSetting.defaultSettings()); } public static JsAPIs with(CorpSetting corpSetting) { JsAPIs jsAPIs = new JsAPIs(); jsAPIs.setWxClient(QyWxClientFactory.getInstance().with(corpSetting)); return jsAPIs; } public void setWxClient(WxClient wxClient) { this.wxClient = wxClient; } /** * 调用微信JS接口的临时票据 */ private synchronized void getJsAPITicket(){ if(jsAPITicket == null || jsAPITicket.expired()) {//double check String url = WxEndpoint.get("url.jsapi.ticket.get"); String response = wxClient.get(url); this.jsAPITicket = APITicket.fromJson(response); } } /** * 获取管理组临时票据 */ private synchronized void getJsAPIGroupTicket(){ if(jsAPIGroupTicket == null || jsAPIGroupTicket.expired()) {//double check String url = WxEndpoint.get("url.jsapi.ticket.group.get"); String response = wxClient.get(url); this.jsAPIGroupTicket = APITicket.fromJson(response); } } /** * 创建JsAPI签名 * @param url * @return */ public JsAPISignature createJsAPISignature(String url){ if(jsAPITicket == null || jsAPITicket.expired()) { getJsAPITicket(); } long timestamp = System.currentTimeMillis() / 1000; String nonce = RandomStringGenerator.getRandomStringByLength(16); String ticket = jsAPITicket.getTicket(); try { String signature = SHA1.getSHA1("jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url); JsAPISignature jsAPISignature = new JsAPISignature(); jsAPISignature.setAppId(wxClient.getClientId()); jsAPISignature.setNonce(nonce); jsAPISignature.setTimestamp(timestamp); jsAPISignature.setSignature(signature); jsAPISignature.setUrl(url); return jsAPISignature; } catch (AesException e) { logger.error("createJsAPISignature failed", e); throw new WxRuntimeException(999, e.getMessage()); } } /** * 创建企业号管理组权限签名 * @param url * @return */ public JsAPISignature createJsAPIGroupSignature(String url){ if(jsAPIGroupTicket == null || jsAPIGroupTicket.expired()) { getJsAPIGroupTicket(); } long timestamp = System.currentTimeMillis() / 1000; String nonce = RandomStringGenerator.getRandomStringByLength(16); String ticket = jsAPIGroupTicket.getTicket(); try { String signature = SHA1.getSHA1("group_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url); JsAPISignature jsAPISignature = new JsAPISignature(); jsAPISignature.setAppId(wxClient.getClientId()); jsAPISignature.setNonce(nonce); jsAPISignature.setTimestamp(timestamp); jsAPISignature.setSignature(signature); jsAPISignature.setUrl(url); jsAPISignature.setGroupId(jsAPIGroupTicket.getGroupId()); return jsAPISignature; } catch (AesException e) { logger.error("createJsAPIGroupSignature failed", e); throw new WxRuntimeException(999, e.getMessage()); } } public static class APITicket { @JsonProperty("group_id") private String groupId; private String ticket; @JsonProperty("expires_in") private long expiresIn; private long expiresTill; public static APITicket fromJson(String json) { return JsonMapper.defaultMapper().fromJson(json, APITicket.class); } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public long getExpiresIn() { return expiresIn; } public void setExpiresIn(long expiresIn) { this.expiresIn = expiresIn; this.expiresTill = System.currentTimeMillis() + (expiresIn * 1000) - 60000; } public long getExpiresTill() { return expiresTill; } public boolean expired() { return System.currentTimeMillis() > expiresTill; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.lab.ocp.day11; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * @author MB-study */ public class MapGroup1 { public static void main(String[] args) { String[] fruits = {"apple", "apple", "watermelon", "apple", "orange", "watermelon", "banana", "coconut", "orange"}; //apple:3 watermelon:2, orange:2, banana:1, coconut:1 //分組 Map<String, Long> map = Stream.of(fruits) .collect(Collectors.groupingBy(fruit -> fruit, Collectors.counting())); System.out.println(map); Map<String, Long> map2 = Stream.of(fruits) .collect(Collectors.groupingBy(String::toString , Collectors.counting())); System.out.println(map2); Map<String, Long> map3 = Stream.of(fruits) .collect(Collectors.groupingBy(Function.identity() , Collectors.counting())); System.out.println(map3); } }
package org.gluu.oxtrust.api.server.api.impl; import org.slf4j.Logger; import io.swagger.v3.oas.annotations.info.Contact; import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.info.License; import io.swagger.v3.oas.annotations.OpenAPIDefinition; @OpenAPIDefinition ( info = @Info ( title = "oxTrust API", version = "4.0.0", description = "This is an API for Gluu Server's oxTrust administrative interface. Go to https://gluu.org for more information", termsOfService = "https://www.gluu.org/terms/", contact = @Contact(url="https://gluu.org",name="Gluu Support",email="contact@gluu.org"), license = @License(name = "Gluu Support License", url = "https://www.gluu.org/support-license/") ) ) public class BaseWebResource { protected static final String READ_ACCESS = "oxtrust-api-read"; protected static final String WRITE_ACCESS = "oxtrust-api-write"; public BaseWebResource() { } public void log(Logger logger, Exception e) { logger.debug("++++++++++API-ERROR", e); } public void log(Logger logger, String message) { logger.info(message); } }
package com.mw.portfolio.email.exception; public class EmailCreationException extends EmailException { public EmailCreationException(Throwable cause) { super(cause); } }
package com.example.android.coolweather; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
package com.diegocavalca.agenda; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
import edu.princeton.cs.algs4.*; class ShortestAncestralPath { Digraph G; Digraph reserveG; int s; public ShortestAncestralPath(Digraph G, int s) { this.G = G; this.reserveG = G.reserve(); this.s = s; } public Iterable<Integer> path(int v, int w) { BreadthFirstDirectedPaths bfs = new BreadthFirstDirectedPaths(this.reserveG, this.s); int distV = bfs.distTo(v); int distW = bfs.distTo(w); return distV < distW ? bfs.pathTo(v) : bfs.pathTo(w); } }
/* Copyright 2016 Goldman Sachs. 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 com.gs.fw.common.mithra.test.util; import com.gs.fw.common.mithra.notification.server.ClientNotificationHandler; import com.gs.fw.common.mithra.notification.server.NotificationClient; import com.gs.fw.common.mithra.notification.server.NotificationServer; import com.gs.fw.common.mithra.notification.server.ServerSocketHandler; import junit.framework.TestCase; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestNotificationServer extends TestCase { private NotificationServer server; private int port; private static final String TEST_SUBJECT = "localhost:A"; private static double ERROR_RATE = 0.98; protected void setUp() throws Exception { } private void setupNormalServer() { server = new NotificationServer(0); server.start(); port = server.getPort(); } private void setupUnreliableServer() { server = new UnreliableNotificationServer(0); server.start(); port = server.getPort(); } public void testTwoClients() { setupNormalServer(); RecordingClientHandler handlerOne = new RecordingClientHandler(); NotificationClient first = new NotificationClient("localhost", this.port, handlerOne); first.subscribe(TEST_SUBJECT); first.start(); RecordingClientHandler handlerTwo = new RecordingClientHandler(); NotificationClient second = new NotificationClient("localhost", this.port, handlerTwo); second.subscribe(TEST_SUBJECT); second.start(); server.waitForMessagesReceived(6); byte[] firstMessage = new byte[1]; firstMessage[0] = 100; first.broadcastNotification(TEST_SUBJECT, firstMessage); byte[] secondMessage = new byte[1]; secondMessage[0] = 50; second.broadcastNotification(TEST_SUBJECT, secondMessage); server.waitForMessagesReceived(10); first.waitForAllAcks(); second.waitForAllAcks(); server.waitForAllAcks(); first.waitForAllAcks(); second.waitForAllAcks(); server.waitForAllAcks(); first.shutdown(); second.shutdown(); assertEquals(1, handlerOne.messages.size()); assertEquals(1, handlerTwo.messages.size()); MessageWithSubject firstReceived = handlerOne.messages.get(0); assertEquals(TEST_SUBJECT, firstReceived.getSubject()); assertEquals(1, firstReceived.getMessage().length); assertEquals(50, firstReceived.getMessage()[0]); MessageWithSubject secondReceived = handlerTwo.messages.get(0); assertEquals(TEST_SUBJECT, secondReceived.getSubject()); assertEquals(1, secondReceived.getMessage().length); assertEquals(100, secondReceived.getMessage()[0]); } public void testTwoClientsLargeMessage() { setupNormalServer(); RecordingClientHandler handlerOne = new RecordingClientHandler(); NotificationClient first = new NotificationClient("localhost", this.port, handlerOne); first.subscribe(TEST_SUBJECT); first.start(); RecordingClientHandler handlerTwo = new RecordingClientHandler(); NotificationClient second = new NotificationClient("localhost", this.port, handlerTwo); second.subscribe(TEST_SUBJECT); second.start(); server.waitForMessagesReceived(6); byte[] firstMessage = new byte[5000]; firstMessage[0] = 100; firstMessage[4999] = 50; first.broadcastNotification(TEST_SUBJECT, firstMessage); byte[] secondMessage = new byte[5000]; secondMessage[0] = 50; secondMessage[4999] = 100; second.broadcastNotification(TEST_SUBJECT, secondMessage); server.waitForMessagesReceived(10); first.waitForAllAcks(); second.waitForAllAcks(); server.waitForAllAcks(); first.waitForAllAcks(); second.waitForAllAcks(); server.waitForAllAcks(); first.shutdown(); second.shutdown(); if (handlerTwo.messages.size() < 1) { System.currentTimeMillis(); } assertEquals(1, handlerOne.messages.size()); assertEquals(1, handlerTwo.messages.size()); MessageWithSubject firstReceived = handlerOne.messages.get(0); assertEquals(TEST_SUBJECT, firstReceived.getSubject()); assertEquals(5000, firstReceived.getMessage().length); assertEquals(50, firstReceived.getMessage()[0]); assertEquals(100, firstReceived.getMessage()[4999]); MessageWithSubject secondReceived = handlerTwo.messages.get(0); assertEquals(TEST_SUBJECT, secondReceived.getSubject()); assertEquals(5000, secondReceived.getMessage().length); assertEquals(100, secondReceived.getMessage()[0]); assertEquals(50, secondReceived.getMessage()[4999]); } public void testTwoClientsHundredMessages() { runManyClients(2, 406); } public void testDozenClientsHundredMessages() { runManyClients(12, 14436); } public void testServerThreadFailureHandling() throws InterruptedException { final int failingPortNumber = -6; final CountDownLatch trigger = new CountDownLatch(1); NotificationServer.ExceptionHandler mockHandler = new NotificationServer.ExceptionHandler () { @Override public void handleException(Throwable exception) { trigger.countDown(); } }; server = new NotificationServer(failingPortNumber, mockHandler); server.setDaemon(true); server.start(); assertTrue("Exception handler was not called", trigger.await(1L, TimeUnit.MINUTES)); } public void runManyClients(int clientCount, int expectedServerMessages) { setupNormalServer(); RecordingClientHandler[] handlers = new RecordingClientHandler[clientCount]; NotificationClient clients[] = new NotificationClient[clientCount]; for(int i=0;i< clientCount;i++) { RecordingClientHandler handler = new RecordingClientHandler(); handlers[i] = handler; NotificationClient client = new NotificationClient("localhost", this.port, handler); client.start(); clients[i] = client; } for(int i=0;i< clientCount;i++) { clients[i].subscribe(TEST_SUBJECT); } server.waitForMessagesReceived(clientCount*3); for(int k=0;k<100;k++) { for(int i=0;i< clientCount;i++) { byte[] message = new byte[k*100]; for(int j=0;j<k*100;j++) { message[j] = (byte) j; } clients[i].broadcastNotification(TEST_SUBJECT, message); } } server.waitForMessagesReceived(expectedServerMessages); for(int i=0;i< clientCount;i++) { clients[i].waitForAllAcks(); } server.waitForAllAcks(); for(int i=0;i< clientCount;i++) { clients[i].waitForAllAcks(); } server.waitForAllAcks(); for(int i=0;i< clientCount;i++) { clients[i].shutdown(); } for(int i=0;i< clientCount;i++) { assertEquals((clientCount - 1)*100, handlers[i].messages.size()); for(MessageWithSubject message: handlers[i].messages) { assertEquals(TEST_SUBJECT, message.getSubject()); assertTrue(message.getMessage().length % 100 == 0); for(int j=0;j<message.getMessage().length;j++) { assertEquals((byte) j, message.getMessage()[j]); } } } } public void xtestTwoUnreliableClientsHundredMessages() { runManyClientsUnreliableNetwork(2); } public void xtestDozenUnreliableClientsHundredMessages() { runManyClientsUnreliableNetwork(12); } public void runManyClientsUnreliableNetwork(int clientCount) { setupUnreliableServer(); ERROR_RATE = 1.1; // no errors RecordingClientHandler[] handlers = new RecordingClientHandler[clientCount]; NotificationClient clients[] = new NotificationClient[clientCount]; for(int i=0;i< clientCount;i++) { RecordingClientHandler handler = new RecordingClientHandler(); handlers[i] = handler; NotificationClient client = new UnreliableNotificationClient("localhost", this.port, handler); client.start(); clients[i] = client; } for(int i=0;i< clientCount;i++) { clients[i].subscribe(TEST_SUBJECT); } server.waitForMessagesReceived(clientCount); ERROR_RATE = 0.99; // 1% chance of error. for(int k=0;k<100;k++) { for(int i=0;i< clientCount;i++) { byte[] message = new byte[k*100]; for(int j=0;j<k*100;j++) { message[j] = (byte) j; } clients[i].broadcastNotification(TEST_SUBJECT, message); } } long now = System.currentTimeMillis(); int done = 0; while(done < clientCount) { done = 0; for(int i=0;i< clientCount;i++) { if ((clientCount - 1)*100 > handlers[i].messages.size()) { try { Thread.sleep(100); } catch (InterruptedException e) { //ignore } } else { done++; } if (System.currentTimeMillis() > now + 5*60*1000) { fail("did not complete after 5 minutes"); } } } for(int i=0;i< clientCount;i++) { for(int k = 0;k<handlers[i].messages.size();k++) { MessageWithSubject message = handlers[i].messages.get(k); assertEquals(TEST_SUBJECT, message.getSubject()); assertTrue(message.getMessage().length % 100 == 0); for(int j=0;j<message.getMessage().length;j++) { assertEquals((byte) j, message.getMessage()[j]); } } } } protected void tearDown() throws Exception { server.shutdown(); } private static class MessageWithSubject { private String subject; private byte[] message; private MessageWithSubject(String subject, byte[] message) { this.subject = subject; this.message = message; } public byte[] getMessage() { return message; } public String getSubject() { return subject; } } private static class RecordingClientHandler implements ClientNotificationHandler { private List<MessageWithSubject> messages = new ArrayList<MessageWithSubject>(); public void handleMessage(String subject, byte[] message) { messages.add(new MessageWithSubject(subject, message)); } } private static class UnreliableNotificationServer extends NotificationServer { private UnreliableNotificationServer(int port) { super(port); } protected ServerSocketHandler createServerSocketHandler(Socket incoming) { return new UnreliableServerSocketHandler(incoming, this); } } private static class UnreliableServerSocketHandler extends ServerSocketHandler { private UnreliableServerSocketHandler(Socket socket, NotificationServer server) { super(socket, server); } protected InputStream getInputStreamFromSocket() throws IOException { return new UnreliableInputStream(super.getInputStreamFromSocket()); } protected OutputStream getOutputStreamFromSocket() throws IOException { return new UnreliableOutputStream(super.getOutputStreamFromSocket()); } } private static class UnreliableNotificationClient extends NotificationClient { private UnreliableNotificationClient(String serverHostname, int serverPort, ClientNotificationHandler handler) { super(serverHostname, serverPort, handler); } protected InputStream getInputStreamFromSocket() throws IOException { return new UnreliableInputStream(super.getInputStreamFromSocket()); } protected OutputStream getOutputStreamFromSocket() throws IOException { return new UnreliableOutputStream(super.getOutputStreamFromSocket()); } } private static class UnreliableOutputStream extends OutputStream { private OutputStream out; private UnreliableOutputStream(OutputStream out) { this.out = out; } public void write(int b) throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); out.write(b); } public void write(byte b[]) throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); out.write(b); } public void write(byte b[], int off, int len) throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); out.write(b, off, len); } } private static class UnreliableInputStream extends InputStream { private InputStream in; private UnreliableInputStream(InputStream in) { this.in = in; } public int read() throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); return in.read(); } public int read(byte b[]) throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); return in.read(b); } public int read(byte b[], int off, int len) throws IOException { if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); return in.read(b, off, len); } } }
package com.example.soroushmehraein.flickster.clients; /** * Author: soroushmehraein * Project: Flickster * Date: 7/24/16. */ public class YouTubeClient { public static final String API_KEY = "AIzaSyAV3YmK5cDdqbr8Hm_y22RVcB7mj_qUVWs"; }
/** * The class models a hand of triple in a Big Two card game. * A triple consists of three cards with the same rank. The * card with the highest suit in a triple is referred to as * the top card of this triple. A triple with a higher rank * beats a triple with a lower rank. * * @author Lu Meng * @version 1.0 * @see Hand */ public class Triple extends Hand { /** * a constructor for building a hand with the specified player and list of cards * * @param player the specified player * @param cards the list of cards */ public Triple(CardGamePlayer player, CardList cards) { super(player, cards); this.type = 3; } /** * a method for checking if this is a triple * * @return whether this is a triple */ @Override public boolean isValid() { return this.size() == 3 && this.getCard(0).rank == this.getCard(1).rank && this.getCard(1).rank == this.getCard(2).rank; } /** * a method for returning a string specifying the type of this hand * * @return a string specifying the type of this hand */ @Override public String getType() { return "Triple"; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ranger.services.hdfs; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.server.namenode.INode; import org.apache.hadoop.hdfs.server.namenode.INodeAttributeProvider.AccessControlEnforcer; import org.apache.hadoop.hdfs.server.namenode.INodeAttributes; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.ranger.authorization.hadoop.RangerHdfsAuthorizer; import org.apache.ranger.authorization.hadoop.config.RangerConfiguration; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; /** * Direct tests for the {@link RangerHdfsAuthorizer} without going through the HDFS layer. * */ public class RangerHdfsAuthorizerTest { private final static int SNAPSHOT_ID = 1; private final static String FILE_OWNER = "fileOwner"; private final static String FILE_GROUP = "superGroup"; private static final FsPermission READ_ONLY = new FsPermission(FsAction.READ, FsAction.NONE, FsAction.NONE); private static final FsPermission EXEC_BY_OWNER = new FsPermission(FsAction.EXECUTE, FsAction.NONE, FsAction.NONE); private static RangerHdfsAuthorizer authorizer; private static AccessControlEnforcer rangerControlEnforcer; static class TestFileSystem { final String path; final String[] pathSegments; final INode[] nodes; final INodeAttributes[] attributes; final int ancestorIndex; TestFileSystem(String path) { this.path = path; pathSegments = path.split("/"); nodes = new INode[pathSegments.length]; attributes = new INode[pathSegments.length]; for (int i = 0; i < pathSegments.length; i++) { boolean file = i == pathSegments.length - 1; INode node = createNode(pathSegments, i, FILE_OWNER, FILE_GROUP, file); nodes[i] = node; attributes[i] = node; } ancestorIndex = nodes.length - 2; } public void setFilePermission(FsPermission fsPermission) { when(nodes[nodes.length-1].getFsPermission()).thenReturn(fsPermission); } public void setParentDirectoryPermission(FsPermission fsPermission) { when(nodes[nodes.length-2].getFsPermission()).thenReturn(fsPermission); } /** * Checks that the <b>directory</b> access is <b>allowed</b> for the given user in the given groups. * Throws an exception, if not. */ public void checkDirAccess(FsAction access, String userName, String... groups) throws AccessControlException { final UserGroupInformation user = UserGroupInformation.createUserForTesting(userName, groups); rangerControlEnforcer.checkPermission(FILE_OWNER, FILE_GROUP, user, Arrays.copyOf(attributes, attributes.length - 1), Arrays.copyOf(nodes, nodes.length - 1), new byte[0][0], SNAPSHOT_ID, path, ancestorIndex - 1, false /* doCheckOwner */, null /* ancestorAccess */, null /* parentAccess */ , access, null /* subAccess */ , false /* ignoreEmptyDir */); } /** * Checks that the <b>file</b> access is <b>allowed</b> for the given user in the given groups. * Throws an exception, if not. */ public void checkAccess(FsAction access, String userName, String... groups) throws AccessControlException { final UserGroupInformation user = UserGroupInformation.createUserForTesting(userName, groups); rangerControlEnforcer.checkPermission(FILE_OWNER, FILE_GROUP, user, attributes, nodes, new byte[0][0], SNAPSHOT_ID, path, ancestorIndex, false /* doCheckOwner */, null /* ancestorAccess */, null /* parentAccess */ , access, null /* subAccess */ , false /* ignoreEmptyDir */); } /** * Checks that the <b>file</b> access is <b>blocked</b> for the given user in the given groups. * Throws an exception, if not. */ public void checkAccessBlocked(FsAction access, String userName, String... groups) throws AccessControlException { try { checkAccess(access, userName, groups); Assert.fail("Access should be blocked for " + path + " access=" + access + " for user=" + userName + " groups=" + Arrays.asList(groups)); } catch (AccessControlException ace) { Assert.assertNotNull(ace); } } /** * Checks that the <b>directory</b> access is <b>blocked</b> for the given user in the given groups. * Throws an exception, if not. */ public void checkDirAccessBlocked(FsAction access, String userName, String... groups) throws AccessControlException { try { checkDirAccess(access, userName, groups); Assert.fail("Access should be blocked for parent directory of " + path + " access=" + access + " for user=" + userName + " groups=" + Arrays.asList(groups)); } catch (AccessControlException ace) { Assert.assertNotNull(ace); } } } @BeforeClass public static void setup() { try { File file = File.createTempFile("hdfs-version-site", ".xml"); file.deleteOnExit(); try(final FileOutputStream outStream = new FileOutputStream(file); final OutputStreamWriter writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8)) { writer.write("<configuration>\n" + " <property>\n" + " <name>hdfs.version</name>\n" + " <value>hdfs_version_3.0</value>\n" + " </property>\n" + "</configuration>\n"); } RangerConfiguration config = RangerConfiguration.getInstance(); config.addResource(new org.apache.hadoop.fs.Path(file.toURI())); } catch (Exception exception) { Assert.fail("Cannot create hdfs-version-site file:[" + exception.getMessage() + "]"); } authorizer = new RangerHdfsAuthorizer(); authorizer.start(); AccessControlEnforcer accessControlEnforcer = Mockito.mock(AccessControlEnforcer.class); rangerControlEnforcer = authorizer.getExternalAccessControlEnforcer(accessControlEnforcer); } @AfterClass public static void teardown() { authorizer.stop(); } @Test public void testAccessControlEnforcer() { Assert.assertNotNull("rangerControlEnforcer", rangerControlEnforcer); } @Test public void readTest() throws AccessControlException { readPath("/tmp/tmpdir/data-file2"); } @Test public void readTestUsingTagPolicy() throws Exception { final TestFileSystem fs = new TestFileSystem("/tmp/tmpdir6/data-file2"); fs.setFilePermission(READ_ONLY); // Try to read the files as "bob" - this should be allowed (by the policy - user) fs.checkAccess(null, "bob"); // traverse check fs.checkAccess(FsAction.READ, "bob"); // read check // Now try to read the file as "alice" - this should be allowed (by the policy - group) fs.checkAccess(null, "alice", "IT"); // traverse check fs.checkAccess(FsAction.READ, "alice", "IT"); // read check // Now try to read the file as unknown user "eve" - this should not be allowed fs.checkAccess(null, "eve"); // traverse check fs.checkAccessBlocked(FsAction.READ, "eve"); // read deny check to public // Now try to read the file as user "dave" - this should not be allowed fs.checkAccess(null, "dave"); // traverse check fs.checkAccessBlocked(FsAction.READ, "dave"); // read deny check for public } @Test public void writeTest() throws AccessControlException { final TestFileSystem fs = new TestFileSystem("/tmp/tmpdir2/data-file3"); // Try to write to the file as "bob" - this should be allowed (by the policy - user) fs.checkAccess(null, "bob"); // traverse check fs.checkAccess(FsAction.WRITE, "bob"); // write check // Now try to write to the file as "alice" - this should be allowed (by the policy - group) fs.checkAccess(null, "alice", "IT"); // traverse check fs.checkAccess(FsAction.WRITE, "alice", "IT"); // write check // Now try to write the file as unknown user "eve" - this should not be allowed fs.checkAccessBlocked(null, "eve"); // traverse check fs.checkAccessBlocked(FsAction.WRITE, "eve"); // write deny check for public } @Test public void executeTest() throws AccessControlException { final TestFileSystem fs = new TestFileSystem("/tmp/tmpdir3/data-file2"); fs.setFilePermission(READ_ONLY); fs.setParentDirectoryPermission(EXEC_BY_OWNER); // Try to list the files as "bob" - this should be allowed (by the policy - user) fs.checkDirAccess(null, "bob"); // traverse check fs.checkDirAccess(FsAction.READ_EXECUTE, "bob"); // dir list check // Try to list the directory as "alice" - this should be allowed (by the policy - group) fs.checkDirAccess(null, "alice", "IT"); // traverse check fs.checkDirAccess(FsAction.READ_EXECUTE, "alice", "IT"); // dir list check // Now try to list the directory as unknown user "eve" - this should not be allowed fs.checkDirAccessBlocked(null, "eve"); // traverse check fs.checkDirAccessBlocked(FsAction.READ_EXECUTE, "eve"); // dir list deny check for public } @Test public void HDFSFileNameTokenReadTest() throws AccessControlException { readPath("/tmp/tmpdir4/data-file"); readFailWithPath("/tmp/tmpdir4/t/abc"); } @Test public void HDFSBaseFileNameTokenReadTest() throws AccessControlException { readPath("/tmp/tmpdir5/data-file.txt"); readFailWithPath("/tmp/tmpdir5/data-file.csv"); readFailWithPath("/tmp/tmpdir5/t/data-file.txt"); } private void readFailWithPath(String path) throws AccessControlException { final TestFileSystem fs = new TestFileSystem(path); fs.setFilePermission(READ_ONLY); // Now try to read the file as "bob" - this should NOT be allowed fs.checkAccessBlocked(FsAction.READ, "bob"); // read check // Now try to read the file as "alice" - this should NOT be allowed fs.checkAccessBlocked(FsAction.READ, "alice", "IT"); // read check // Now try to read the file as unknown user "eve" - this should not be allowed fs.checkAccessBlocked(FsAction.READ, "eve", "IT"); // read deny check for public } private void readPath(String path) throws AccessControlException { final TestFileSystem fs = new TestFileSystem(path); fs.setFilePermission(READ_ONLY); // Try to read the files as "bob" - this should be allowed (by the policy - user) fs.checkAccess(null, "bob"); // traverse check fs.checkAccess(FsAction.READ, "bob"); // read check // Now try to read the file as "alice" - this should be allowed (by the policy - group) fs.checkAccess(null, "alice", "IT"); // traverse check fs.checkAccess(FsAction.READ, "alice", "IT"); // read check // Now try to read the file as unknown user "eve" - this should not be allowed fs.checkAccessBlocked(null, "eve"); // traverse deny check for public fs.checkAccessBlocked(FsAction.READ, "eve"); // read deny check for public } private static INode createNode(String[] pathSegments, int i, String owner, String group, boolean file) { String fullPath = StringUtils.join(pathSegments, '/', 0, i+1); String name = pathSegments[i]; INode mock = Mockito.mock(INode.class); try { when(mock.getLocalNameBytes()).thenReturn(name.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } when(mock.getUserName()).thenReturn(owner); when(mock.getGroupName()).thenReturn(group); when(mock.getFullPathName()).thenReturn(fullPath); when(mock.isFile()).thenReturn(file); when(mock.isDirectory()).thenReturn(!file); when(mock.toString()).thenReturn(name); return mock; } }
package io.nadron.protocols.impl; import io.nadron.app.PlayerSession; import io.nadron.handlers.netty.DefaultToServerHandler; import io.nadron.handlers.netty.MessageBufferEventDecoder; import io.nadron.handlers.netty.MessageBufferEventEncoder; import io.nadron.protocols.AbstractNettyProtocol; import io.nadron.util.NettyUtils; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.LengthFieldPrepender; import net.clanwolf.starmap.logging.C3Logger; public class MessageBufferProtocol extends AbstractNettyProtocol { /** * Utility handler provided by netty to add the length of the outgoing * message to the message as a header. */ private LengthFieldPrepender lengthFieldPrepender; private MessageBufferEventDecoder messageBufferEventDecoder; private MessageBufferEventEncoder messageBufferEventEncoder; public MessageBufferProtocol() { super("MESSAGE_BUFFER_PROTOCOL"); } @Override public void applyProtocol(PlayerSession playerSession) { C3Logger.info("Going to apply " + getProtocolName() + " on session: " + playerSession); ChannelPipeline pipeline = NettyUtils .getPipeLineOfConnection(playerSession); // Upstream handlers or encoders (i.e towards server) are added to // pipeline now. pipeline.addLast("lengthDecoder", createLengthBasedFrameDecoder()); pipeline.addLast("messageBufferEventDecoder",messageBufferEventDecoder); pipeline.addLast("eventHandler", new DefaultToServerHandler( playerSession)); // Downstream handlers - Filter for data which flows from server to // client. Note that the last handler added is actually the first // handler for outgoing data. pipeline.addLast("lengthFieldPrepender", lengthFieldPrepender); pipeline.addLast("messageBufferEventEncoder",messageBufferEventEncoder); } public LengthFieldPrepender getLengthFieldPrepender() { return lengthFieldPrepender; } public void setLengthFieldPrepender(LengthFieldPrepender lengthFieldPrepender) { this.lengthFieldPrepender = lengthFieldPrepender; } public MessageBufferEventDecoder getMessageBufferEventDecoder() { return messageBufferEventDecoder; } public void setMessageBufferEventDecoder( MessageBufferEventDecoder messageBufferEventDecoder) { this.messageBufferEventDecoder = messageBufferEventDecoder; } public MessageBufferEventEncoder getMessageBufferEventEncoder() { return messageBufferEventEncoder; } public void setMessageBufferEventEncoder( MessageBufferEventEncoder messageBufferEventEncoder) { this.messageBufferEventEncoder = messageBufferEventEncoder; } }
package lv.ctco.cukes.core.internal.templating; import com.google.common.base.Optional; import com.google.inject.Inject; import com.google.inject.Singleton; import lv.ctco.cukes.core.CukesOptions; import lv.ctco.cukes.core.internal.context.GlobalWorldFacade; import lv.ctco.cukes.core.internal.context.InflateContext; import org.rythmengine.Rythm; import java.util.HashMap; import java.util.Map; @Singleton @InflateContext public class TemplatingEngine { @Inject GlobalWorldFacade world; private Boolean isBodyTemplatesEnabled() { return world.getBoolean(CukesOptions.REQUEST_BODY_TEMPLATES_ENABLED); } public String processBody(String body) { if (isBodyTemplatesEnabled()) { final Map<String, String> rythmParams = new HashMap<String, String>(); for (String key : world.keys()) { Optional<String> value = world.get(key); if (value.isPresent() && body.contains("@" + key)) rythmParams.put(key, value.get()); } return Rythm.render(body, rythmParams); } return body; } }
/** * Copyright (c) 2013-2022 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.analytic; import java.io.IOException; import java.io.Serializable; import org.locationtech.geowave.core.store.adapter.TransientAdapterStore; import org.locationtech.geowave.core.store.api.DataTypeAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Support for adapter stores that are Serializable. Rather than for an adapter store to serialize * its state, wrap an adapter store. If the adapter store is not serializable, then log a warning * message upon serialization. */ public class SerializableAdapterStore implements TransientAdapterStore, Serializable { /** */ private static final long serialVersionUID = 1L; static final Logger LOGGER = LoggerFactory.getLogger(SerializableAdapterStore.class); transient TransientAdapterStore adapterStore; public SerializableAdapterStore() {} public SerializableAdapterStore(final TransientAdapterStore adapterStore) { super(); this.adapterStore = adapterStore; } private TransientAdapterStore getAdapterStore() { if (adapterStore == null) { throw new IllegalStateException("AdapterStore has not been initialized"); } return adapterStore; } @Override public void addAdapter(final DataTypeAdapter<?> adapter) { getAdapterStore().addAdapter(adapter); } @Override public DataTypeAdapter<?> getAdapter(final String typeName) { return getAdapterStore().getAdapter(typeName); } @Override public boolean adapterExists(final String typeName) { return getAdapterStore().adapterExists(typeName); } @Override public DataTypeAdapter<?>[] getAdapters() { return getAdapterStore().getAdapters(); } @Override public void removeAll() { getAdapterStore().removeAll(); } private void writeObject(final java.io.ObjectOutputStream out) throws IOException { if (adapterStore instanceof Serializable) { out.writeBoolean(true); out.writeObject(adapterStore); } else { out.writeBoolean(false); } } private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { adapterStore = (TransientAdapterStore) in.readObject(); } else { LOGGER.warn("Unable to initialized AdapterStore; the store is not serializable"); } } @Override public void removeAdapter(final String typeName) { getAdapterStore().removeAdapter(typeName); } }
package com.squareup.square.models; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonGetter; import com.squareup.square.http.client.HttpContext; /** * This is a model class for V1Timecard type. */ public class V1Timecard { /** * Initialization constructor. * @param employeeId * @param id * @param deleted * @param clockinTime * @param clockoutTime * @param clockinLocationId * @param clockoutLocationId * @param createdAt * @param updatedAt * @param regularSecondsWorked * @param overtimeSecondsWorked * @param doubletimeSecondsWorked */ @JsonCreator public V1Timecard( @JsonProperty("employee_id") String employeeId, @JsonProperty("id") String id, @JsonProperty("deleted") Boolean deleted, @JsonProperty("clockin_time") String clockinTime, @JsonProperty("clockout_time") String clockoutTime, @JsonProperty("clockin_location_id") String clockinLocationId, @JsonProperty("clockout_location_id") String clockoutLocationId, @JsonProperty("created_at") String createdAt, @JsonProperty("updated_at") String updatedAt, @JsonProperty("regular_seconds_worked") Double regularSecondsWorked, @JsonProperty("overtime_seconds_worked") Double overtimeSecondsWorked, @JsonProperty("doubletime_seconds_worked") Double doubletimeSecondsWorked) { this.id = id; this.employeeId = employeeId; this.deleted = deleted; this.clockinTime = clockinTime; this.clockoutTime = clockoutTime; this.clockinLocationId = clockinLocationId; this.clockoutLocationId = clockoutLocationId; this.createdAt = createdAt; this.updatedAt = updatedAt; this.regularSecondsWorked = regularSecondsWorked; this.overtimeSecondsWorked = overtimeSecondsWorked; this.doubletimeSecondsWorked = doubletimeSecondsWorked; } private HttpContext httpContext; private final String id; private final String employeeId; private final Boolean deleted; private final String clockinTime; private final String clockoutTime; private final String clockinLocationId; private final String clockoutLocationId; private final String createdAt; private final String updatedAt; private final Double regularSecondsWorked; private final Double overtimeSecondsWorked; private final Double doubletimeSecondsWorked; public HttpContext getContext() { return httpContext; } /** * Getter for Id. * The timecard's unique ID. */ @JsonGetter("id") public String getId() { return this.id; } /** * Getter for EmployeeId. * The ID of the employee the timecard is associated with. */ @JsonGetter("employee_id") public String getEmployeeId() { return this.employeeId; } /** * Getter for Deleted. * If true, the timecard was deleted by the merchant, and it is no longer valid. */ @JsonGetter("deleted") public Boolean getDeleted() { return this.deleted; } /** * Getter for ClockinTime. * The clock-in time for the timecard, in ISO 8601 format. */ @JsonGetter("clockin_time") public String getClockinTime() { return this.clockinTime; } /** * Getter for ClockoutTime. * The clock-out time for the timecard, in ISO 8601 format. Provide this value only if importing timecard information from another system. */ @JsonGetter("clockout_time") public String getClockoutTime() { return this.clockoutTime; } /** * Getter for ClockinLocationId. * The ID of the location the employee clocked in from. We strongly reccomend providing a clockin_location_id. Square uses the clockin_location_id to determine a timecard’s timezone and overtime rules. */ @JsonGetter("clockin_location_id") public String getClockinLocationId() { return this.clockinLocationId; } /** * Getter for ClockoutLocationId. * The ID of the location the employee clocked out from. Provide this value only if importing timecard information from another system. */ @JsonGetter("clockout_location_id") public String getClockoutLocationId() { return this.clockoutLocationId; } /** * Getter for CreatedAt. * The time when the timecard was created, in ISO 8601 format. */ @JsonGetter("created_at") public String getCreatedAt() { return this.createdAt; } /** * Getter for UpdatedAt. * The time when the timecard was most recently updated, in ISO 8601 format. */ @JsonGetter("updated_at") public String getUpdatedAt() { return this.updatedAt; } /** * Getter for RegularSecondsWorked. * The total number of regular (non-overtime) seconds worked in the timecard. */ @JsonGetter("regular_seconds_worked") public Double getRegularSecondsWorked() { return this.regularSecondsWorked; } /** * Getter for OvertimeSecondsWorked. * The total number of overtime seconds worked in the timecard. */ @JsonGetter("overtime_seconds_worked") public Double getOvertimeSecondsWorked() { return this.overtimeSecondsWorked; } /** * Getter for DoubletimeSecondsWorked. * The total number of doubletime seconds worked in the timecard. */ @JsonGetter("doubletime_seconds_worked") public Double getDoubletimeSecondsWorked() { return this.doubletimeSecondsWorked; } @Override public int hashCode() { return Objects.hash(id, employeeId, deleted, clockinTime, clockoutTime, clockinLocationId, clockoutLocationId, createdAt, updatedAt, regularSecondsWorked, overtimeSecondsWorked, doubletimeSecondsWorked); } @Override public boolean equals(Object obj) { if(obj == this) { return true; } if(!(obj instanceof V1Timecard)) { return false; } V1Timecard v1Timecard = (V1Timecard) obj; return Objects.equals(id, v1Timecard.id) && Objects.equals(employeeId, v1Timecard.employeeId) && Objects.equals(deleted, v1Timecard.deleted) && Objects.equals(clockinTime, v1Timecard.clockinTime) && Objects.equals(clockoutTime, v1Timecard.clockoutTime) && Objects.equals(clockinLocationId, v1Timecard.clockinLocationId) && Objects.equals(clockoutLocationId, v1Timecard.clockoutLocationId) && Objects.equals(createdAt, v1Timecard.createdAt) && Objects.equals(updatedAt, v1Timecard.updatedAt) && Objects.equals(regularSecondsWorked, v1Timecard.regularSecondsWorked) && Objects.equals(overtimeSecondsWorked, v1Timecard.overtimeSecondsWorked) && Objects.equals(doubletimeSecondsWorked, v1Timecard.doubletimeSecondsWorked); } /** * Builds a new {@link V1Timecard.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link V1Timecard.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(employeeId) .id(getId()) .deleted(getDeleted()) .clockinTime(getClockinTime()) .clockoutTime(getClockoutTime()) .clockinLocationId(getClockinLocationId()) .clockoutLocationId(getClockoutLocationId()) .createdAt(getCreatedAt()) .updatedAt(getUpdatedAt()) .regularSecondsWorked(getRegularSecondsWorked()) .overtimeSecondsWorked(getOvertimeSecondsWorked()) .doubletimeSecondsWorked(getDoubletimeSecondsWorked()); return builder; } /** * Class to build instances of {@link V1Timecard} */ public static class Builder { private HttpContext httpContext; private String employeeId; private String id; private Boolean deleted; private String clockinTime; private String clockoutTime; private String clockinLocationId; private String clockoutLocationId; private String createdAt; private String updatedAt; private Double regularSecondsWorked; private Double overtimeSecondsWorked; private Double doubletimeSecondsWorked; /** * Initialization constructor */ public Builder(String employeeId) { this.employeeId = employeeId; } /** * Setter for httpContext * @param httpContext * @return Builder */ public Builder httpContext(HttpContext httpContext) { this.httpContext = httpContext; return this; } /** * Setter for employeeId * @param employeeId * @return Builder */ public Builder employeeId(String employeeId) { this.employeeId = employeeId; return this; } /** * Setter for id * @param id * @return Builder */ public Builder id(String id) { this.id = id; return this; } /** * Setter for deleted * @param deleted * @return Builder */ public Builder deleted(Boolean deleted) { this.deleted = deleted; return this; } /** * Setter for clockinTime * @param clockinTime * @return Builder */ public Builder clockinTime(String clockinTime) { this.clockinTime = clockinTime; return this; } /** * Setter for clockoutTime * @param clockoutTime * @return Builder */ public Builder clockoutTime(String clockoutTime) { this.clockoutTime = clockoutTime; return this; } /** * Setter for clockinLocationId * @param clockinLocationId * @return Builder */ public Builder clockinLocationId(String clockinLocationId) { this.clockinLocationId = clockinLocationId; return this; } /** * Setter for clockoutLocationId * @param clockoutLocationId * @return Builder */ public Builder clockoutLocationId(String clockoutLocationId) { this.clockoutLocationId = clockoutLocationId; return this; } /** * Setter for createdAt * @param createdAt * @return Builder */ public Builder createdAt(String createdAt) { this.createdAt = createdAt; return this; } /** * Setter for updatedAt * @param updatedAt * @return Builder */ public Builder updatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } /** * Setter for regularSecondsWorked * @param regularSecondsWorked * @return Builder */ public Builder regularSecondsWorked(Double regularSecondsWorked) { this.regularSecondsWorked = regularSecondsWorked; return this; } /** * Setter for overtimeSecondsWorked * @param overtimeSecondsWorked * @return Builder */ public Builder overtimeSecondsWorked(Double overtimeSecondsWorked) { this.overtimeSecondsWorked = overtimeSecondsWorked; return this; } /** * Setter for doubletimeSecondsWorked * @param doubletimeSecondsWorked * @return Builder */ public Builder doubletimeSecondsWorked(Double doubletimeSecondsWorked) { this.doubletimeSecondsWorked = doubletimeSecondsWorked; return this; } /** * Builds a new {@link V1Timecard} object using the set fields. * @return {@link V1Timecard} */ public V1Timecard build() { V1Timecard model = new V1Timecard(employeeId, id, deleted, clockinTime, clockoutTime, clockinLocationId, clockoutLocationId, createdAt, updatedAt, regularSecondsWorked, overtimeSecondsWorked, doubletimeSecondsWorked); model.httpContext = httpContext; return model; } } }
package hj.action.DesignPatterns.Memento.example.game; /** * <p>Title : 负责人:保存存档</p> * <p>Description : </p> * <p>Date : 2019-02-20 </p> * * @author : hejie */ public class Caretaker { Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
/* * Copyright 2010 Google Inc. * * 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 com.google.jstestdriver.protocol; import java.util.List; /** * The response command to a received {@link CommandResponse} to the server, * that contains all received response ids for this streaming session * from the browsers. * * Having two sets of client server relations (JsTestDriverClient and JsTestDriverServer, * JsTestDriverServer and Browser) really screws up the semantics. * * @author corbinrsmith@gmail.com (Cory Smith) * */ public class BrowserStreamAcknowledged { private final List<String> parameters; private final String command = "streamAcknowledged"; public BrowserStreamAcknowledged(List<String> recievedResponseIds) { this.parameters = recievedResponseIds; } public List<String> getParameters() { return parameters; } public String getCommand() { return command; } }
package com.coolweather.app.model; public class County extends Space{ private int cityId; public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
package org.openpaas.paasta.portal.api.service; import org.cloudfoundry.client.v2.buildpacks.ListBuildpacksRequest; import org.cloudfoundry.client.v2.buildpacks.ListBuildpacksResponse; import org.cloudfoundry.client.v2.buildpacks.UpdateBuildpackRequest; import org.openpaas.paasta.portal.api.common.Common; import org.openpaas.paasta.portal.api.model.BuildPack; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Service; import java.util.Map; @EnableAsync @Service public class BuildPackServiceV2 extends Common{ /** * 빌드팩 리스트 조회 * * @return the boolean * @throws Exception the exception */ public Map<String, Object> getBuildPacks() throws Exception { ListBuildpacksResponse listBuildpacksResponse = cloudFoundryClient(connectionContext(), tokenProvider()) .buildpacks() .list(ListBuildpacksRequest.builder().build()) .block(); return objectMapper.convertValue(listBuildpacksResponse, Map.class); } /** * 빌드팩 정보 수정 * * @param buildPack the buildPack * @return the boolean * @throws Exception the exception */ public boolean updateBuildPack(BuildPack buildPack) throws Exception { cloudFoundryClient(connectionContext(), tokenProvider()) .buildpacks() .update(UpdateBuildpackRequest.builder() .buildpackId(buildPack.getGuid().toString()) .position(buildPack.getPosition()) .enabled(buildPack.getEnable()) .locked(buildPack.getLock()) .build()) .block(); return true; } }
package ash.vm; import ash.lang.*; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.stream.Collectors; public final class JavaMethod implements Serializable { private static final Class<?>[] EMPTY_CLASSES = new Class<?>[]{}; private static final long serialVersionUID = -933603269059202413L; private static final Map<String, JavaMethod> CACHE = new WeakHashMap<>(); private String methodFullName; private Class<?> clazz; transient private List<Method> candidateMethods; public static JavaMethod create(Symbol symbol) { String methodName = symbol.name; JavaMethod javaMethod = CACHE.get(methodName); if (javaMethod == null) { javaMethod = new JavaMethod(symbol); CACHE.put(methodName, javaMethod); } return javaMethod; } private JavaMethod(Symbol symbol) { methodFullName = symbol.name; if (methodFullName.charAt(0) == '.') return; try { clazz = loadClassBySymbol(symbol); loadCandidateMethod(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Class<?> loadClassBySymbol(Symbol symbolName) throws ClassNotFoundException { return Class.forName(getFullClassPath(symbolName.name)); } private static String getFullClassPath(String classpath) { int sepPos = classpath.indexOf('/'); String path = sepPos != -1 ? classpath.substring(0, sepPos) : classpath; if (Character.isUpperCase(path.charAt(0)) && path.indexOf('.') == -1) { return "java.lang." + path; } return path; } @Override public String toString() { return methodFullName; } private List<Method> loadCandidateMethod() { if (clazz != null && candidateMethods == null) { candidateMethods = filterMethod(clazz.getMethods(), getStaticMemberName()); } return candidateMethods; } private static List<Method> filterMethod(Method[] methods, final String methodName) { return Arrays.asList(methods).stream().filter(m -> m.getName().equals(methodName)).collect(Collectors.toList()); } private String getStaticMemberName() { return methodFullName.substring(methodFullName.indexOf('/') + 1); } public Object call(Object[] args) { List<Method> candidateMethods = loadCandidateMethod(); Object rst = candidateMethods != null && 0 < candidateMethods.size() ? callReflectMethod(args, candidateMethods) : callCustomMethod(args); if (rst == null) return BasicType.NIL; else if (rst instanceof Boolean) return ListUtils.transformBoolean(((Boolean) rst).booleanValue()); return rst; } private Object callCustomMethod(Object[] args) { switch (methodFullName) { case ".new": return reflectCreateObject(args); default: if (methodFullName.startsWith(".$")) { return readField(methodFullName.substring(2), args); } else if (methodFullName.charAt(0) == '.') { return callInstanceMethod(methodFullName.substring(1), args); } throw new UnsupportedOperationException("Unsupport Custom Method Call:" + methodFullName); } } private static Object callReflectMethod(Object[] args, List<Method> candidateMethods) { try { if (candidateMethods.size() == 1) { return candidateMethods.get(0).invoke(null, args); } else { return matchMethod(candidateMethods, getParameterTypes(args)).invoke(null, args); } } catch (Exception e) { throw new RuntimeException(e); } } private static Object callInstanceMethod(String methodName, Object[] args) { try { Object[] argsArray = subArray(args, 1); Method[] methods = args[0].getClass().getMethods(); Method matchMethod = matchMethod(filterMethod(methods, methodName), getParameterTypes(argsArray)); matchMethod.setAccessible(true); return matchMethod.invoke(args[0], argsArray); } catch (Exception e) { throw new RuntimeException(e); } } private static Object readField(String fieldName, Object[] args) { try { if (args[0] instanceof Symbol) { return loadClassBySymbol((Symbol) args[0]).getField(fieldName).get(null); } else { return args[0].getClass().getField(fieldName).get(args[0]); } } catch (Exception e) { throw new RuntimeException(e); } } public static boolean instanceOf(Class<?> valClass, Class<?> clazz) { return clazz == valClass || clazz.isAssignableFrom(valClass); } private static Object reflectCreateObject(Object[] args) { try { Class<?> clazz = loadClassBySymbol((Symbol) args[0]); Object[] newArgs = subArray(args, 1); Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 1) { return constructors[0].newInstance(newArgs); } else { return matchConstructor(Arrays.asList(constructors), getParameterTypes(newArgs)).newInstance(newArgs); } } catch (Exception e) { throw new RuntimeException(e); } } private static Object[] subArray(Object[] args, int startIndex) { Object[] newArgs = new Object[args.length - startIndex]; System.arraycopy(args, startIndex, newArgs, 0, newArgs.length); return newArgs; } private static Method matchMethod(List<Method> candidateMethods, final Class<?>[] targetParameterTypes) { return candidateMethods.stream() .filter(m -> strictMatch(m.getParameterTypes(), targetParameterTypes)).findFirst() .orElseGet(() -> candidateMethods.stream() .filter(m -> fuzzyMatch(m.getParameterTypes(), targetParameterTypes)) .findFirst().orElse(null)); } private static Constructor<?> matchConstructor(List<Constructor<?>> candidateConstructors, final Class<?>[] targetParameterTypes) { return candidateConstructors.stream() .filter(c -> strictMatch(c.getParameterTypes(), targetParameterTypes)) .findFirst().orElseGet(() -> candidateConstructors.stream() .filter(c -> fuzzyMatch(c.getParameterTypes(), targetParameterTypes)) .findFirst().orElse(null)); } private static Class<?>[] getParameterTypes(Object[] args) { return Arrays.asList(args).stream().map(Object::getClass).toArray(Class[]::new); } // int match to Integer ignore Float private static boolean strictMatch(Class<?>[] methodParameterTypes, Class<?>[] targetParameterTypes) { if (methodParameterTypes.length != targetParameterTypes.length) return false; for (int i = 0; i < targetParameterTypes.length; i++) { if (methodParameterTypes[i].isPrimitive() && STRICT_PRIMITIVE_CLASS_MAP.get(methodParameterTypes[i]) == targetParameterTypes[i]) { } else if (instanceOf(targetParameterTypes[i], methodParameterTypes[i])) { } else { return false; } } return true; } private static boolean fuzzyMatch(Class<?>[] methodParameterTypes, Class<?>[] targetParameterTypes) { if (methodParameterTypes.length != targetParameterTypes.length) return false; for (int i = 0; i < targetParameterTypes.length; i++) { if (methodParameterTypes[i].isPrimitive() && PRIMITIVE_CLASS_MAP.get(methodParameterTypes[i]).contains(targetParameterTypes[i])) { } else if (instanceOf(targetParameterTypes[i], methodParameterTypes[i])) { } else { return false; } } return true; } private static final PersistentMap<Class<?>, Class<?>> STRICT_PRIMITIVE_CLASS_MAP = new PersistentMap<>( boolean.class, Boolean.class, byte.class, Byte.class, char.class, Character.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class ); private static final PersistentMap<Class<?>, PersistentSet<Class<?>>> PRIMITIVE_CLASS_MAP = new PersistentMap<>( boolean.class, new PersistentSet<>(Boolean.class), byte.class, new PersistentSet<>(Byte.class, Character.class), char.class, new PersistentSet<>(Byte.class, Character.class), short.class, new PersistentSet<>(Byte.class, Character.class, Short.class), int.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class), long.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Long.class), float.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Float.class), double.class, new PersistentSet<>(Byte.class, Character.class, Short.class, Integer.class, Float.class, Double.class) ); }
package com.aice.pierotateview.listener; import com.google.android.material.appbar.AppBarLayout; public abstract class AppBarLayoutStateChangeListener implements AppBarLayout.OnOffsetChangedListener{ public enum State{ EXPANDED,//展开 COLLAPSED,//折叠 INTERMEDIATE//中间状态 } private State mCurrentState = State.INTERMEDIATE; @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset == 0) { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED); } mCurrentState = State.EXPANDED; } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED); } mCurrentState = State.COLLAPSED; } else { onStateChanged(appBarLayout, State.INTERMEDIATE); mCurrentState = State.INTERMEDIATE; } } public abstract void onStateChanged(AppBarLayout appBarLayout, State state); }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.workdocs.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.workdocs.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreateFolderRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateFolderRequestProtocolMarshaller implements Marshaller<Request<CreateFolderRequest>, CreateFolderRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/api/v1/folders") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AmazonWorkDocs").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreateFolderRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateFolderRequest> marshall(CreateFolderRequest createFolderRequest) { if (createFolderRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreateFolderRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, createFolderRequest); protocolMarshaller.startMarshalling(); CreateFolderRequestMarshaller.getInstance().marshall(createFolderRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
package com.weirblog.vo; import com.fasterxml.jackson.annotation.JsonProperty; /** * 淘宝IP解析 * @author weir * */ public class IpInfoVO { private String ip; private String country; private String area; private String region; private String city; private String county; private String isp; @JsonProperty("country_id") private Integer countryId; @JsonProperty("area_id") private Integer areaId; @JsonProperty("region_id") private Integer regionId; @JsonProperty("city_id") private Integer cityId; @JsonProperty("county_id") private Integer countyId; @JsonProperty("isp_id") private Integer ispId; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getIsp() { return isp; } public void setIsp(String isp) { this.isp = isp; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; } public Integer getAreaId() { return areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; } public Integer getRegionId() { return regionId; } public void setRegionId(Integer regionId) { this.regionId = regionId; } public Integer getCityId() { return cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; } public Integer getCountyId() { return countyId; } public void setCountyId(Integer countyId) { this.countyId = countyId; } public Integer getIspId() { return ispId; } public void setIspId(Integer ispId) { this.ispId = ispId; } @Override public String toString() { return "IpInfoVO [ip=" + ip + ", country=" + country + ", area=" + area + ", region=" + region + ", city=" + city + ", county=" + county + ", isp=" + isp + ", countryId=" + countryId + ", areaId=" + areaId + ", regionId=" + regionId + ", cityId=" + cityId + ", countyId=" + countyId + ", ispId=" + ispId + "]"; } }
/* * Copyright (c) 2016, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.lir.alloc.trace; import static org.graalvm.compiler.lir.LIRValueUtil.asVariable; import static org.graalvm.compiler.lir.LIRValueUtil.isVariable; import java.util.ArrayList; import java.util.BitSet; import java.util.EnumSet; import org.graalvm.compiler.core.common.cfg.AbstractBlockBase; import org.graalvm.compiler.core.common.cfg.Loop; import org.graalvm.compiler.debug.DebugContext; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.debug.Indent; import org.graalvm.compiler.lir.InstructionValueConsumer; import org.graalvm.compiler.lir.LIR; import org.graalvm.compiler.lir.LIRInstruction; import org.graalvm.compiler.lir.LIRInstruction.OperandFlag; import org.graalvm.compiler.lir.LIRInstruction.OperandMode; import org.graalvm.compiler.lir.Variable; import org.graalvm.compiler.lir.gen.LIRGenerationResult; import org.graalvm.compiler.lir.phases.AllocationPhase; import org.graalvm.compiler.lir.ssa.SSAUtil; import jdk.vm.ci.code.TargetDescription; import jdk.vm.ci.meta.Value; /** * Constructs {@link GlobalLivenessInfo global liveness information}. */ public final class GlobalLivenessAnalysisPhase extends AllocationPhase { @Override protected void run(TargetDescription target, LIRGenerationResult lirGenRes, AllocationContext context) { assert SSAUtil.verifySSAForm(lirGenRes.getLIR()); Analyser ssiBuilder = new Analyser(lirGenRes.getLIR()); ssiBuilder.build(); ssiBuilder.finish(); GlobalLivenessInfo livenessInfo = ssiBuilder.getLivenessInfo(); assert livenessInfo.verify(lirGenRes.getLIR()); context.contextAdd(livenessInfo); } private final class Analyser { private static final int LOG_LEVEL = DebugContext.INFO_LEVEL; /** * Bit map specifying which operands are live upon entry to this block. These are values * used in this block or any of its successors where such value are not defined in this * block. The bit index of an operand is its {@linkplain #operandNumber operand number}. */ private final BitSet[] liveIns; /** * Bit map specifying which operands are live upon exit from this block. These are values * used in a successor block that are either defined in this block or were live upon entry * to this block. The bit index of an operand is its {@linkplain #operandNumber operand * number}. */ private final BitSet[] liveOuts; private final AbstractBlockBase<?>[] blocks; private final Value[] operands; private final LIR lir; private final GlobalLivenessInfo.Builder livenessInfoBuilder; Analyser(LIR lir) { int numBlocks = lir.getControlFlowGraph().getBlocks().length; this.liveIns = new BitSet[numBlocks]; this.liveOuts = new BitSet[numBlocks]; this.blocks = lir.getControlFlowGraph().getBlocks(); this.lir = lir; this.operands = new Value[lir.numVariables()]; this.livenessInfoBuilder = new GlobalLivenessInfo.Builder(lir); } private BitSet getLiveIn(final AbstractBlockBase<?> block) { return liveIns[block.getId()]; } private BitSet getLiveOut(final AbstractBlockBase<?> block) { return liveOuts[block.getId()]; } private void setLiveIn(final AbstractBlockBase<?> block, final BitSet liveIn) { liveIns[block.getId()] = liveIn; } private void setLiveOut(final AbstractBlockBase<?> block, final BitSet liveOut) { liveOuts[block.getId()] = liveOut; } private void buildIntern() { computeLiveness(); } /** * Gets the size of the {@link #liveIns} and {@link #liveOuts} sets for a basic block. */ private int liveSetSize() { return lir.numVariables(); } private int operandNumber(Value operand) { if (isVariable(operand)) { return asVariable(operand).index; } throw GraalError.shouldNotReachHere("Can only handle Variables: " + operand); } /** * Computes live sets for each block. */ @SuppressWarnings("try") private void computeLiveness() { // iterate all blocks DebugContext debug = lir.getDebug(); for (int i = blocks.length - 1; i >= 0; i--) { final AbstractBlockBase<?> block = blocks[i]; try (Indent indent = debug.logAndIndent(LOG_LEVEL, "compute local live sets for block %s", block)) { final BitSet liveIn = mergeLiveSets(block); setLiveOut(block, (BitSet) liveIn.clone()); InstructionValueConsumer useConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { processUse(liveIn, operand); } }; InstructionValueConsumer defConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { processDef(liveIn, op, operand); } }; if (debug.isLogEnabled()) { debug.log(LOG_LEVEL, "liveOut B%d %s", block.getId(), getLiveOut(block)); } // iterate all instructions of the block ArrayList<LIRInstruction> instructions = getLIR().getLIRforBlock(block); for (int j = instructions.size() - 1; j >= 0; j--) { final LIRInstruction op = instructions.get(j); try (Indent indent2 = debug.logAndIndent(LOG_LEVEL, "handle op %d: %s", op.id(), op)) { op.visitEachOutput(defConsumer); op.visitEachTemp(defConsumer); op.visitEachState(useConsumer); op.visitEachAlive(useConsumer); op.visitEachInput(useConsumer); } } // end of instruction iteration setLiveIn(block, liveIn); if (block.isLoopHeader()) { handleLoopHeader(block.getLoop(), liveIn); } if (debug.isLogEnabled()) { debug.log(LOG_LEVEL, "liveIn B%d %s", block.getId(), getLiveIn(block)); } } } // end of block iteration } /** * All variables live at the beginning of a loop are live throughout the loop. */ private void handleLoopHeader(Loop<?> loop, BitSet live) { for (AbstractBlockBase<?> block : loop.getBlocks()) { getLiveIn(block).or(live); getLiveOut(block).or(live); } } private BitSet mergeLiveSets(final AbstractBlockBase<?> block) { assert block != null; final BitSet liveOut = new BitSet(liveSetSize()); for (AbstractBlockBase<?> successor : block.getSuccessors()) { BitSet succLiveIn = getLiveIn(successor); if (succLiveIn != null) { liveOut.or(succLiveIn); } else { assert successor.isLoopHeader() : "Successor of " + block + " not yet processed and not loop header: " + successor; } } return liveOut; } private void processUse(final BitSet liveGen, Value operand) { if (isVariable(operand)) { int operandNum = operandNumber(operand); liveGen.set(operandNum); DebugContext debug = lir.getDebug(); if (debug.isLogEnabled()) { debug.log(LOG_LEVEL, "liveGen for operand %d(%s)", operandNum, operand); } } } private void processDef(final BitSet liveGen, LIRInstruction op, Value operand) { if (isVariable(operand)) { recordVariable(op, asVariable(operand)); int operandNum = operandNumber(operand); if (operands[operandNum] == null) { operands[operandNum] = operand; } liveGen.clear(operandNum); DebugContext debug = lir.getDebug(); if (debug.isLogEnabled()) { debug.log(LOG_LEVEL, "liveKill for operand %d(%s)", operandNum, operand); } } } private LIR getLIR() { return lir; } public void build() { buildIntern(); // check that the liveIn set of the first block is empty AbstractBlockBase<?> startBlock = getLIR().getControlFlowGraph().getStartBlock(); if (getLiveIn(startBlock).cardinality() != 0) { // bailout if this occurs in product mode. throw new GraalError("liveIn set of first block must be empty: " + getLiveIn(startBlock)); } } @SuppressWarnings("try") public void finish() { // iterate all blocks in reverse order for (AbstractBlockBase<?> block : (AbstractBlockBase<?>[]) lir.getControlFlowGraph().getBlocks()) { try (Indent indent = lir.getDebug().logAndIndent(LOG_LEVEL, "Finish Block %s", block)) { buildIncoming(block); buildOutgoing(block); } } } public GlobalLivenessInfo getLivenessInfo() { assert livenessInfoBuilder != null : "No liveness info collected"; return livenessInfoBuilder.createLivenessInfo(); } private void buildIncoming(AbstractBlockBase<?> block) { if (!GlobalLivenessInfo.storesIncoming(block)) { assert block.getPredecessorCount() == 1; assert GlobalLivenessInfo.storesOutgoing(block.getPredecessors()[0]) : "No incoming liveness info: " + block; return; } final int[] liveInArray; if (block.getPredecessorCount() == 0) { // start block assert getLiveIn(block).isEmpty() : "liveIn for start block is not empty? " + getLiveIn(block); liveInArray = livenessInfoBuilder.emptySet; } else { /* * Collect live out of predecessors since there might be values not used in this * block which might cause out/in mismatch. Per construction the live sets of all * predecessors are equal. */ BitSet predLiveOut = getLiveOut(block.getPredecessors()[0]); liveInArray = predLiveOut.isEmpty() ? livenessInfoBuilder.emptySet : bitSetToIntArray(predLiveOut); } livenessInfoBuilder.setIncoming(block, liveInArray); // reuse the same array for outgoing variables in predecessors for (AbstractBlockBase<?> pred : block.getPredecessors()) { livenessInfoBuilder.setOutgoing(pred, liveInArray); } } private void buildOutgoing(AbstractBlockBase<?> block) { BitSet liveOut = getLiveOut(block); if (!GlobalLivenessInfo.storesOutgoing(block)) { assert GlobalLivenessInfo.storesOutgoing(block) || block.getSuccessorCount() == 1; assert GlobalLivenessInfo.storesOutgoing(block) || GlobalLivenessInfo.storesIncoming(block.getSuccessors()[0]) : "No outgoing liveness info: " + block; return; } int[] liveOutArray = liveOut.isEmpty() ? livenessInfoBuilder.emptySet : bitSetToIntArray(liveOut); livenessInfoBuilder.setOutgoing(block, liveOutArray); // reuse the same array for incoming variables in successors for (AbstractBlockBase<?> succ : block.getSuccessors()) { livenessInfoBuilder.setIncoming(succ, liveOutArray); } } private int[] bitSetToIntArray(BitSet live) { int[] vars = new int[live.cardinality()]; int cnt = 0; for (int i = live.nextSetBit(0); i >= 0; i = live.nextSetBit(i + 1), cnt++) { vars[cnt] = i; } return vars; } private void recordVariable(LIRInstruction op, Variable var) { livenessInfoBuilder.addVariable(op, var); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.orc.mapred; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.orc.TypeDescription; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * An in-memory representation of a union type. */ public final class OrcUnion implements WritableComparable<OrcUnion> { private byte tag; private WritableComparable object; private final TypeDescription schema; public OrcUnion(TypeDescription schema) { this.schema = schema; } public void set(int tag, WritableComparable object) { this.tag = (byte) tag; this.object = object; } public byte getTag() { return tag; } public Writable getObject() { return object; } @Override public boolean equals(Object other) { if (other == null || other.getClass() != OrcUnion.class) { return false; } OrcUnion oth = (OrcUnion) other; if (tag != oth.tag) { return false; } else if (object == null) { return oth.object == null; } else { return object.equals(oth.object); } } @Override public int hashCode() { int result = tag; if (object != null) { result ^= object.hashCode(); } return result; } @Override public String toString() { return "uniontype(" + Integer.toString(tag & 0xff) + ", " + object + ")"; } @Override public void write(DataOutput output) throws IOException { output.writeByte(tag); output.writeBoolean(object != null); if (object != null) { object.write(output); } } @Override public void readFields(DataInput input) throws IOException { byte oldTag = tag; tag = input.readByte(); if (input.readBoolean()) { if (oldTag != tag || object == null) { object = OrcStruct.createValue(schema.getChildren().get(tag)); } object.readFields(input); } else { object = null; } } @Override public int compareTo(OrcUnion other) { if (other == null) { return -1; } int result = schema.compareTo(other.schema); if (result != 0) { return result; } if (tag != other.tag) { return tag - other.tag; } if (object == null) { return other.object == null ? 0 : 1; } return object.compareTo(other.object); } }
// Copyright 2018 Google Inc. // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.fhir.wrappers; import static com.google.common.truth.Truth.assertThat; import com.google.common.io.Files; import com.google.devtools.build.runfiles.Runfiles; import com.google.fhir.r4.core.Extension; import com.google.fhir.stu3.google.EventLabel; import com.google.fhir.stu3.google.EventTrigger; import com.google.fhir.stu3.google.PrimitiveHasNoValue; import com.google.protobuf.Message; import com.google.protobuf.TextFormat; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link ExtensionWrapper}. */ @RunWith(JUnit4.class) public final class ExtensionWrapperTest { private TextFormat.Parser textParser; private Runfiles runfiles; /** Read the specifed prototxt file from the testdata directory and parse it. */ private void mergeText(java.lang.String filename, Message.Builder builder) throws IOException { File file = new File(runfiles.rlocation("com_google_fhir/testdata/stu3/google/" + filename)); textParser.merge(Files.asCharSource(file, StandardCharsets.UTF_8).read(), builder); } private <T extends Message> void testMerge(java.lang.String name, T template) throws IOException { // Parse the input. Extension.Builder extensionBuilder = Extension.newBuilder(); Message.Builder goldenBuilder = template.newBuilderForType(); mergeText(name + ".message.prototxt", goldenBuilder); mergeText(name + ".extension.prototxt", extensionBuilder); java.util.List<T> messages = ExtensionWrapper.of(Collections.singletonList(extensionBuilder.build())) .getMatchingExtensions(template); assertThat(messages).containsExactly(goldenBuilder.build()); } private void testExpand(java.lang.String name, Message.Builder builder) throws IOException { // Parse the input. Extension.Builder extensionBuilder = Extension.newBuilder(); mergeText(name + ".message.prototxt", builder); mergeText(name + ".extension.prototxt", extensionBuilder); java.util.List<Extension> result = ExtensionWrapper.of().add(builder).build(); assertThat(result).containsExactly(extensionBuilder.build()); } @Before public void setUp() throws IOException { textParser = TextFormat.getParser(); runfiles = Runfiles.create(); } /** Test merging of an Extension into a PrimitiveHasNoValue message. */ @Test public void mergePrimitiveHasNoValue() throws Exception { testMerge("primitive_has_no_value", PrimitiveHasNoValue.getDefaultInstance()); testMerge("empty", PrimitiveHasNoValue.getDefaultInstance()); } /** Test expanding a PrimitiveHasNoValue into an Extension. */ @Test public void expandPrimitiveHasNoValue() throws Exception { testExpand("primitive_has_no_value", PrimitiveHasNoValue.newBuilder()); testExpand("empty", PrimitiveHasNoValue.newBuilder()); } /** Test merging of an Extension into an EventTrigger message. */ @Test public void mergeEventTrigger() throws Exception { testMerge("trigger", EventTrigger.getDefaultInstance()); } /** Test expanding an EventTrigger into an Extension. */ @Test public void expandEventTrigger() throws Exception { testExpand("trigger", EventTrigger.newBuilder()); } /** Test merging of an Extension into an EventLabel message. */ @Test public void mergeEventLabel() throws Exception { testMerge("label", EventLabel.getDefaultInstance()); } /** Test expanding an EventLabel into an Extension. */ @Test public void expandEventLabel() throws Exception { testExpand("label", EventLabel.newBuilder()); } }
package com.test.springboot.rabbitmq.application.service; import java.util.stream.Stream; /** * @author pedro */ public interface BaseService<DOMAIN, ID> { DOMAIN insert(DOMAIN domain); DOMAIN update(DOMAIN domain); void delete(ID id); DOMAIN findById(ID id); Stream<DOMAIN> findAll(); }