max_stars_repo_path
stringlengths
6
1.02k
max_stars_repo_name
stringlengths
6
114
max_stars_count
int64
0
191k
id
stringlengths
1
8
content
stringlengths
1
1.05M
score
float64
-0.93
3.95
int_score
int64
0
4
src/org/opengts/util/DatagramMessage.java
paragp/GTS-PreUAT
0
1
// ---------------------------------------------------------------------------- // Copyright 2007-2015, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Change History: // 2007/11/28 <NAME> // -Initial release // 2009/01/28 <NAME> // -Improved command-line interface // 2015/08/16 <NAME> // -Added "udpTest" command-line option // ---------------------------------------------------------------------------- package org.opengts.util; import java.lang.*; import java.util.*; import java.io.*; import java.net.*; /** *** A class for sending and recieving datagram messages [CHECK] **/ public class DatagramMessage { // ------------------------------------------------------------------------ protected DatagramSocket datagramSocket = null; protected DatagramPacket sendPacket = null; protected DatagramPacket recvPacket = null; /** *** For subclassing only **/ protected DatagramMessage() { } /** *** Constructor for receiving messages *** @param port The port to use *** @throws IOException if a socket error occurs *** @throws UnknownHostException if the IP adress of the host could not be *** determined **/ public DatagramMessage(int port) throws IOException, UnknownHostException { this.datagramSocket = new DatagramSocket(port); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @throws IOException if a socket error occurs *** @throws UnknownHostException if the IP adress of the host could not be *** determined **/ public DatagramMessage(String destHost, int destPort) throws IOException, UnknownHostException { this(InetAddress.getByName(destHost), destPort); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @throws IOException if a socket error occurs **/ public DatagramMessage(InetAddress destHost, int destPort) throws IOException { this.datagramSocket = new DatagramSocket(); this.setRemoteHost(destHost, destPort); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @param bindPort The local port to bind *** @throws IOException if a socket error occurs *** @throws UnknownHostException if the IP adress of the host could not be *** determined **/ public DatagramMessage(String destHost, int destPort, int bindPort) throws IOException, UnknownHostException { this(InetAddress.getByName(destHost), destPort, bindPort, null); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @param bindPort The local port to bind *** @param bindAddr The local address to bind *** @throws IOException if a socket error occurs *** @throws UnknownHostException if the IP adress of the host could not be *** determined **/ public DatagramMessage(String destHost, int destPort, int bindPort, String bindAddr) throws IOException, UnknownHostException { this(InetAddress.getByName(destHost), destPort, bindPort, (!StringTools.isBlank(bindAddr)? InetAddress.getByName(bindAddr) : null)); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @param bindPort The local port to bind *** @throws IOException if a socket error occurs **/ public DatagramMessage(InetAddress destHost, int destPort, int bindPort) throws IOException { this(destHost, destPort, bindPort, null); } /** *** Constructor for sending messages *** @param destHost The remote(destination) host address *** @param destPort The remote(destination) port to use *** @param bindPort The local port to bind *** @param bindAddr The local address to bind *** @throws IOException if a socket error occurs **/ public DatagramMessage(InetAddress destHost, int destPort, int bindPort, InetAddress bindAddr) throws IOException { if (bindPort <= 0) { this.datagramSocket = new DatagramSocket(); } else if (bindAddr == null) { this.datagramSocket = new DatagramSocket(bindPort); } else { this.datagramSocket = new DatagramSocket(bindPort, bindAddr); } this.setRemoteHost(destHost, destPort); } // ------------------------------------------------------------------------ /** *** Closes the datagram socket **/ public void close() throws IOException { this.datagramSocket.close(); } // ------------------------------------------------------------------------ /** *** Set the remote(destination) host *** @param host The remote host address *** @param port The remote host port *** @throws IOException if an error occurs **/ public void setRemoteHost(String host, int port) throws IOException { this.setRemoteHost(InetAddress.getByName(host), port); } /** *** Set the remote(destination) host *** @param host The remote host address *** @param port The remote host port *** @throws IOException if an error occurs **/ public void setRemoteHost(InetAddress host, int port) throws IOException { if (this.sendPacket != null) { this.sendPacket.setAddress(host); this.sendPacket.setPort(port); } else { this.sendPacket = new DatagramPacket(new byte[0], 0, host, port); } } /** *** Gets the datagram packet to be sent *** @return The datagram packet to be sent **/ public DatagramPacket getSendPacket() { return this.sendPacket; } // ------------------------------------------------------------------------ /** *** Send a String to the remote host *** @param msg The String to send to the remote host *** @throws IOException if the string is null or a socket error occurs **/ public void send(String msg) throws IOException { this.send(StringTools.getBytes(msg)); } /** *** Send an array of bytes to the remote host *** @param data The array of bytes to send to the remote host *** @throws IOException if the string is null or a socket error occurs **/ public void send(byte data[]) throws IOException { if (data != null) { this.send(data, data.length); } else { throw new IOException("Nothing to send"); } } /** *** Send an array of bytes to the remote host *** @param data The array of bytes to send to the remote host *** @param len The length of the data *** @throws IOException if the string is null or a socket error occurs **/ public void send(byte data[], int len) throws IOException { this.send(data, len, 1); } /** *** Send an array of bytes to the remote host *** @param data The array of bytes to send to the remote host *** @param len The length of the data *** @param count The number of times to send the message *** @throws IOException if the string is null or a socket error occurs **/ public void send(byte data[], int len, int count) throws IOException { if (this.sendPacket == null) { throw new IOException("'setRemoteHost' not specified"); } else if ((data == null) || (len <= 0) || (count <= 0)) { throw new IOException("Nothing to send"); } else { this.sendPacket.setData(data); this.sendPacket.setLength(len); for (; count > 0; count--) { this.datagramSocket.send(this.sendPacket); } } } // ------------------------------------------------------------------------ private static final int DEFAULT_PACKET_SIZE = 1024; /** *** Receive an array of bytes *** @param maxBuffSize The maximum buffer size *** @return The recieved packet as a byte array *** @throws IOException if a socket error occurs **/ public byte[] receive(int maxBuffSize) throws IOException { /* receive data */ byte dbuff[] = new byte[(maxBuffSize > 0)? maxBuffSize : DEFAULT_PACKET_SIZE]; this.recvPacket = new DatagramPacket(dbuff, dbuff.length); this.datagramSocket.receive(this.recvPacket); byte newBuff[] = new byte[this.recvPacket.getLength()]; System.arraycopy(this.recvPacket.getData(), 0, newBuff, 0, this.recvPacket.getLength()); /* return received data */ return newBuff; } /** *** Gets the DatagramPacket last recieved [CHECK] *** @return The DatagramPacket last recieved **/ public DatagramPacket getReceivePacket() { return this.recvPacket; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Example receiver: // bin/exeJava org.opengts.util.DatagramMessage -port=39000 -recv -echo // Example transmitter: // bin/exeJava org.opengts.util.DatagramMessage -host=localhost -port=39000 -send=hello -recv private static final String ARG_HOST[] = new String[] { "host" , "h" }; private static final String ARG_PORT[] = new String[] { "port" , "p" }; private static final String ARG_BINDADDR[] = new String[] { "bindAddr" }; private static final String ARG_BINDPORT[] = new String[] { "bindPort" }; private static final String ARG_SEND[] = new String[] { "send" }; private static final String ARG_RECEIVE[] = new String[] { "recv", "receive" }; private static final String ARG_ECHO[] = new String[] { "echo", }; private static final String ARG_STRESSTEST[] = new String[] { "udpStressTest" }; // "msgs/sec,seconds,pktSize" private static void usage() { Print.logInfo("Usage:"); Print.logInfo(" java ... " + DatagramMessage.class.getName() + " {options}"); Print.logInfo("'Send' Options:"); Print.logInfo(" -bindAddr=<ip> The local bind address"); Print.logInfo(" -bindPort=<port> The local bind port"); Print.logInfo(" -host=<host> The destination host"); Print.logInfo(" -port=<port> The destination port"); Print.logInfo(" -send=<data> The data to send (prefix with '0x' for hex data)"); Print.logInfo(" -recv Set to 'receive' mode after sending"); Print.logInfo("'Receive' Options:"); Print.logInfo(" -port=<port> The port on which to listen for incoming data"); Print.logInfo(" -recv Set to 'receive' mode"); Print.logInfo(" -echo Echo received packet back to sender (implies '-recv')"); System.exit(1); } /** *** Main entry point for testing/debugging *** @param argv Comand-line arguments **/ public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); String host = RTConfig.getString(ARG_HOST, null); int port = RTConfig.getInt(ARG_PORT, 0); boolean cmdEcho = RTConfig.hasProperty(ARG_ECHO); boolean cmdRecv = RTConfig.hasProperty(ARG_RECEIVE); /* send data */ if (RTConfig.hasProperty(ARG_SEND)) { if (StringTools.isBlank(host)) { Print.logError("Target host not specified"); usage(); } if (port <= 0) { Print.logError("Target port not specified"); usage(); } DatagramMessage dgm = null; try { int bindPort = RTConfig.getInt(ARG_BINDPORT, -1); String bindAddr = RTConfig.getString(ARG_BINDADDR, null); dgm = new DatagramMessage(host, port, bindPort, bindAddr); String dataStr = RTConfig.getString(ARG_SEND,"Hello World"); byte send[] = dataStr.startsWith("0x")? StringTools.parseHex(dataStr,null) : dataStr.getBytes(); dgm.send(send); Print.logInfo("Datagram sent to %s:%d", host, port); if (!cmdRecv) { // -- skip attempting to receive message } else if (bindPort <= 0) { Print.logWarn("'-recv' requires '-bindPort', receive ignored."); } else { Print.sysPrintln("Waiting for incoming data on port %d ...", bindPort); byte recv[] = dgm.receive(1000); // timeout? SocketAddress sa = dgm.getReceivePacket().getSocketAddress(); if (sa instanceof InetSocketAddress) { int recvPort = dgm.getReceivePacket().getPort(); InetAddress hostAddr = ((InetSocketAddress)sa).getAddress(); Print.logInfo("Received from '" + hostAddr + ":" + recvPort + "' - 0x" + StringTools.toHexString(recv)); } } } catch (Throwable th) { Print.logException("Error", th); System.exit(99); } finally { try { if (dgm != null) { dgm.close(); } } catch (IOException ioe) { // -- ignore } } System.exit(0); } /* receive data */ if (cmdRecv || cmdEcho) { if (port <= 0) { Print.logError("Target port not specified"); usage(); } if (!StringTools.isBlank(host)) { Print.logWarn("Specified 'host' will be ignored"); } DatagramMessage dgm = null; try { dgm = new DatagramMessage(port); Print.sysPrintln("Waiting for incoming data on port %d ...", port); byte recv[] = dgm.receive(1000); SocketAddress sa = dgm.getReceivePacket().getSocketAddress(); if (sa instanceof InetSocketAddress) { InetAddress hostAddr = ((InetSocketAddress)sa).getAddress(); int recvPort = dgm.getReceivePacket().getPort(); Print.logInfo("Received from host "+hostAddr+"["+recvPort+"]: 0x" + StringTools.toHexString(recv)); if (cmdEcho) { try { Thread.sleep(500L); } catch (Throwable th) { /* ignore */ } Print.sysPrintln("Echoing packet back to sender ..."); dgm.setRemoteHost(hostAddr, recvPort); dgm.send(recv); } } } catch (Throwable th) { Print.logException("Error", th); System.exit(99); } finally { try { if (dgm != null) { dgm.close(); } } catch (IOException ioe) { // -- ignore } } System.exit(0); } /* show usage */ usage(); } }
0.976563
1
engine/src/org/pentaho/di/job/entries/ssh2get/JobEntrySSH2GET.java
krivera-pentaho/pentaho-kettle
1
9
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.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 org.pentaho.di.job.entries.ssh2get; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileType; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.resource.ResourceReference; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; import com.trilead.ssh2.Connection; import com.trilead.ssh2.HTTPProxyData; import com.trilead.ssh2.KnownHosts; import com.trilead.ssh2.SFTPv3Client; import com.trilead.ssh2.SFTPv3DirectoryEntry; import com.trilead.ssh2.SFTPv3FileAttributes; import com.trilead.ssh2.SFTPv3FileHandle; /** * This defines a SSH2 GET job entry. * * @author Samatar * @since 17-12-2007 * */ public class JobEntrySSH2GET extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntrySSH2GET.class; // for i18n purposes, needed by Translator2!! private String serverName; private String userName; private String password; private String serverPort; private String ftpDirectory; private String localDirectory; private String wildcard; private boolean onlyGettingNewFiles; /* Don't overwrite files */ private boolean usehttpproxy; private String httpProxyHost; private String httpproxyport; private String httpproxyusername; private String httpProxyPassword; private boolean publicpublickey; private String keyFilename; private String keyFilePass; private boolean useBasicAuthentication; private String afterFtpPut; private String destinationfolder; private boolean createdestinationfolder; private boolean cachehostkey; private int timeout; boolean createtargetfolder; boolean includeSubFolders; static KnownHosts database = new KnownHosts(); int nbfilestoget = 0; int nbgot = 0; int nbrerror = 0; public JobEntrySSH2GET( String n ) { super( n, "" ); serverName = null; publicpublickey = false; keyFilename = null; keyFilePass = null; usehttpproxy = false; httpProxyHost = null; httpproxyport = null; httpproxyusername = null; httpProxyPassword = <PASSWORD>; serverPort = "22"; useBasicAuthentication = false; afterFtpPut = "do_nothing"; destinationfolder = null; includeSubFolders = false; createdestinationfolder = false; createtargetfolder = false; cachehostkey = false; timeout = 0; } public JobEntrySSH2GET() { this( "" ); } public Object clone() { JobEntrySSH2GET je = (JobEntrySSH2GET) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer( 128 ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( "servername", serverName ) ); retval.append( " " ).append( XMLHandler.addTagValue( "username", userName ) ); retval.append( " " ).append( XMLHandler.addTagValue( "password", Encr.encryptPasswordIfNotUsingVariables( getPassword() ) ) ); retval.append( " " ).append( XMLHandler.addTagValue( "serverport", serverPort ) ); retval.append( " " ).append( XMLHandler.addTagValue( "ftpdirectory", ftpDirectory ) ); retval.append( " " ).append( XMLHandler.addTagValue( "localdirectory", localDirectory ) ); retval.append( " " ).append( XMLHandler.addTagValue( "wildcard", wildcard ) ); retval.append( " " ).append( XMLHandler.addTagValue( "only_new", onlyGettingNewFiles ) ); retval.append( " " ).append( XMLHandler.addTagValue( "usehttpproxy", usehttpproxy ) ); retval.append( " " ).append( XMLHandler.addTagValue( "httpproxyhost", httpProxyHost ) ); retval.append( " " ).append( XMLHandler.addTagValue( "httpproxyport", httpproxyport ) ); retval.append( " " ).append( XMLHandler.addTagValue( "httpproxyusername", httpproxyusername ) ); retval.append( " " ).append( XMLHandler.addTagValue( "httpproxypassword", httpProxyPassword ) ); retval.append( " " ).append( XMLHandler.addTagValue( "publicpublickey", publicpublickey ) ); retval.append( " " ).append( XMLHandler.addTagValue( "keyfilename", keyFilename ) ); retval.append( " " ).append( XMLHandler.addTagValue( "keyfilepass", keyFilePass ) ); retval.append( " " ).append( XMLHandler.addTagValue( "usebasicauthentication", useBasicAuthentication ) ); retval.append( " " ).append( XMLHandler.addTagValue( "afterftpput", afterFtpPut ) ); retval.append( " " ).append( XMLHandler.addTagValue( "destinationfolder", destinationfolder ) ); retval .append( " " ).append( XMLHandler.addTagValue( "createdestinationfolder", createdestinationfolder ) ); retval.append( " " ).append( XMLHandler.addTagValue( "cachehostkey", cachehostkey ) ); retval.append( " " ).append( XMLHandler.addTagValue( "timeout", timeout ) ); retval.append( " " ).append( XMLHandler.addTagValue( "createtargetfolder", createtargetfolder ) ); retval.append( " " ).append( XMLHandler.addTagValue( "includeSubFolders", includeSubFolders ) ); return retval.toString(); } public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep, IMetaStore metaStore ) throws KettleXMLException { try { super.loadXML( entrynode, databases, slaveServers ); serverName = XMLHandler.getTagValue( entrynode, "servername" ); userName = XMLHandler.getTagValue( entrynode, "username" ); password = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( entrynode, "password" ) ); serverPort = XMLHandler.getTagValue( entrynode, "serverport" ); ftpDirectory = XMLHandler.getTagValue( entrynode, "ftpdirectory" ); localDirectory = XMLHandler.getTagValue( entrynode, "localdirectory" ); wildcard = XMLHandler.getTagValue( entrynode, "wildcard" ); onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "only_new" ) ); usehttpproxy = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "usehttpproxy" ) ); httpProxyHost = XMLHandler.getTagValue( entrynode, "httpproxyhost" ); httpproxyport = XMLHandler.getTagValue( entrynode, "httpproxyport" ); httpproxyusername = XMLHandler.getTagValue( entrynode, "httpproxyusername" ); httpProxyPassword = XMLHandler.getTagValue( entrynode, "httpproxypassword" ); publicpublickey = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "publicpublickey" ) ); keyFilename = XMLHandler.getTagValue( entrynode, "keyfilename" ); keyFilePass = XMLHandler.getTagValue( entrynode, "keyfilepass" ); useBasicAuthentication = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "usebasicauthentication" ) ); afterFtpPut = XMLHandler.getTagValue( entrynode, "afterftpput" ); destinationfolder = XMLHandler.getTagValue( entrynode, "destinationfolder" ); createdestinationfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "createdestinationfolder" ) ); cachehostkey = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "cachehostkey" ) ); timeout = Const.toInt( XMLHandler.getTagValue( entrynode, "timeout" ), 0 ); createtargetfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "createtargetfolder" ) ); includeSubFolders = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "includeSubFolders" ) ); } catch ( KettleXMLException xe ) { throw new KettleXMLException( BaseMessages.getString( PKG, "JobSSH2GET.Log.UnableLoadXML", xe.getMessage() ) ); } } public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers ) throws KettleException { try { serverName = rep.getJobEntryAttributeString( id_jobentry, "servername" ); userName = rep.getJobEntryAttributeString( id_jobentry, "username" ); password = Encr.decryptPasswordOptionallyEncrypted( rep.getJobEntryAttributeString( id_jobentry, "password" ) ); serverPort = rep.getJobEntryAttributeString( id_jobentry, "serverport" ); ftpDirectory = rep.getJobEntryAttributeString( id_jobentry, "ftpdirectory" ); localDirectory = rep.getJobEntryAttributeString( id_jobentry, "localdirectory" ); wildcard = rep.getJobEntryAttributeString( id_jobentry, "wildcard" ); onlyGettingNewFiles = rep.getJobEntryAttributeBoolean( id_jobentry, "only_new" ); usehttpproxy = rep.getJobEntryAttributeBoolean( id_jobentry, "usehttpproxy" ); httpProxyHost = rep.getJobEntryAttributeString( id_jobentry, "httpproxyhost" ); httpproxyusername = rep.getJobEntryAttributeString( id_jobentry, "httpproxyusername" ); httpProxyPassword = rep.getJobEntryAttributeString( id_jobentry, "httpproxypassword" ); publicpublickey = rep.getJobEntryAttributeBoolean( id_jobentry, "publicpublickey" ); keyFilename = rep.getJobEntryAttributeString( id_jobentry, "keyfilename" ); keyFilePass = rep.getJobEntryAttributeString( id_jobentry, "keyfilepass" ); useBasicAuthentication = rep.getJobEntryAttributeBoolean( id_jobentry, "usebasicauthentication" ); afterFtpPut = rep.getJobEntryAttributeString( id_jobentry, "afterftpput" ); destinationfolder = rep.getJobEntryAttributeString( id_jobentry, "destinationfolder" ); createdestinationfolder = rep.getJobEntryAttributeBoolean( id_jobentry, "createdestinationfolder" ); cachehostkey = rep.getJobEntryAttributeBoolean( id_jobentry, "cachehostkey" ); timeout = (int) rep.getJobEntryAttributeInteger( id_jobentry, "timeout" ); createtargetfolder = rep.getJobEntryAttributeBoolean( id_jobentry, "createtargetfolder" ); includeSubFolders = rep.getJobEntryAttributeBoolean( id_jobentry, "includeSubFolders" ); } catch ( KettleException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobSSH2GET.Log.UnableLoadRep", "" + id_jobentry, dbe.getMessage() ) ); } } public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException { try { rep.saveJobEntryAttribute( id_job, getObjectId(), "servername", serverName ); rep.saveJobEntryAttribute( id_job, getObjectId(), "username", userName ); rep.saveJobEntryAttribute( id_job, getObjectId(), "password", Encr .encryptPasswordIfNotUsingVariables( password ) ); rep.saveJobEntryAttribute( id_job, getObjectId(), "serverport", serverPort ); rep.saveJobEntryAttribute( id_job, getObjectId(), "ftpdirectory", ftpDirectory ); rep.saveJobEntryAttribute( id_job, getObjectId(), "localdirectory", localDirectory ); rep.saveJobEntryAttribute( id_job, getObjectId(), "wildcard", wildcard ); rep.saveJobEntryAttribute( id_job, getObjectId(), "only_new", onlyGettingNewFiles ); rep.saveJobEntryAttribute( id_job, getObjectId(), "usehttpproxy", usehttpproxy ); rep.saveJobEntryAttribute( id_job, getObjectId(), "httpproxyhost", httpProxyHost ); rep.saveJobEntryAttribute( id_job, getObjectId(), "httpproxyport", httpproxyport ); rep.saveJobEntryAttribute( id_job, getObjectId(), "httpproxyusername", httpproxyusername ); rep.saveJobEntryAttribute( id_job, getObjectId(), "httpproxypassword", httpProxyPassword ); rep.saveJobEntryAttribute( id_job, getObjectId(), "publicpublickey", publicpublickey ); rep.saveJobEntryAttribute( id_job, getObjectId(), "keyfilename", keyFilename ); rep.saveJobEntryAttribute( id_job, getObjectId(), "keyfilepass", keyFilePass ); rep.saveJobEntryAttribute( id_job, getObjectId(), "usebasicauthentication", useBasicAuthentication ); rep.saveJobEntryAttribute( id_job, getObjectId(), "afterftpput", afterFtpPut ); rep.saveJobEntryAttribute( id_job, getObjectId(), "destinationfolder", destinationfolder ); rep.saveJobEntryAttribute( id_job, getObjectId(), "createdestinationfolder", createdestinationfolder ); rep.saveJobEntryAttribute( id_job, getObjectId(), "cachehostkey", cachehostkey ); rep.saveJobEntryAttribute( id_job, getObjectId(), "timeout", timeout ); rep.saveJobEntryAttribute( id_job, getObjectId(), "createtargetfolder", createtargetfolder ); rep.saveJobEntryAttribute( id_job, getObjectId(), "includeSubFolders", includeSubFolders ); } catch ( KettleDatabaseException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobSSH2GET.Log.UnableSaveRep", "" + id_job, dbe .getMessage() ) ); } } /** * @return Returns the directory. */ public String getFtpDirectory() { return ftpDirectory; } /** * @param directory * The directory to set. */ public void setFtpDirectory( String directory ) { this.ftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password * The password to set. */ public void setPassword( String password ) { this.password = password; } /** * @return Returns the afterftpput. */ public String getAfterFTPPut() { return afterFtpPut; } /** * @param afterFtpPut * The action after (FTP/SSH) transfer to execute */ public void setAfterFTPPut( String afterFtpPut ) { this.afterFtpPut = afterFtpPut; } /** * @param proxyPassword * The httpproxypassword to set. */ public void setHTTPProxyPassword( String proxyPassword ) { this.httpProxyPassword = proxyPassword; } /** * @return Returns the password. */ public String getHTTPProxyPassword() { return httpProxyPassword; } /** * @param keyFilePass * The key file pass to set. */ public void setKeyFilePass( String keyFilePass ) { this.keyFilePass = keyFilePass; } /** * @return Returns the key file pass. */ public String getKeyFilePass() { return keyFilePass; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName * The serverName to set. */ public void setServerName( String serverName ) { this.serverName = serverName; } /** * @param proxyhost * The httpproxyhost to set. */ public void setHTTPProxyHost( String proxyhost ) { this.httpProxyHost = proxyhost; } /** * @return Returns the HTTP proxy host. */ public String getHTTPProxyHost() { return httpProxyHost; } /** * @param keyfilename * The key filename to set. */ public void setKeyFilename( String keyfilename ) { this.keyFilename = keyfilename; } /** * @return Returns the key filename. */ public String getKeyFilename() { return keyFilename; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName * The userName to set. */ public void setUserName( String userName ) { this.userName = userName; } /** * @param proxyusername * The httpproxyusername to set. */ public void setHTTPProxyUsername( String proxyusername ) { this.httpproxyusername = proxyusername; } /** * @return Returns the userName. */ public String getHTTPProxyUsername() { return httpproxyusername; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard * The wildcard to set. */ public void setWildcard( String wildcard ) { this.wildcard = wildcard; } /** * @return Returns the localDirectory. */ public String getlocalDirectory() { return localDirectory; } /** * @param localDirectory * The localDirectory to set. */ public void setlocalDirectory( String localDirectory ) { this.localDirectory = localDirectory; } /** * @return Returns the onlyGettingNewFiles. */ public boolean isOnlyGettingNewFiles() { return onlyGettingNewFiles; } /** * @param onlyGettingNewFiles * The onlyGettingNewFiles to set. */ public void setOnlyGettingNewFiles( boolean onlyGettingNewFiles ) { this.onlyGettingNewFiles = onlyGettingNewFiles; } /** * @param cachehostkeyin * The cachehostkey to set. */ public void setCacheHostKey( boolean cachehostkeyin ) { this.cachehostkey = cachehostkeyin; } /** * @return Returns the cachehostkey. */ public boolean isCacheHostKey() { return cachehostkey; } /** * @param httpproxy * The usehttpproxy to set. */ public void setUseHTTPProxy( boolean httpproxy ) { this.usehttpproxy = httpproxy; } /** * @return Returns the usehttpproxy. */ public boolean isUseHTTPProxy() { return usehttpproxy; } /** * @return Returns the use basic authentication flag. */ public boolean isUseBasicAuthentication() { return useBasicAuthentication; } /** * @param useBasicAuthentication * The use basic authentication flag to set. */ public void setUseBasicAuthentication( boolean useBasicAuthentication ) { this.useBasicAuthentication = useBasicAuthentication; } /** * @param includeSubFolders * The include sub folders flag to set. */ public void setIncludeSubFolders( boolean includeSubFolders ) { this.includeSubFolders = includeSubFolders; } /** * @return Returns the include sub folders flag. */ public boolean isIncludeSubFolders() { return includeSubFolders; } /** * @param createdestinationfolderin * The createdestinationfolder to set. */ public void setCreateDestinationFolder( boolean createdestinationfolderin ) { this.createdestinationfolder = createdestinationfolderin; } /** * @return Returns the createdestinationfolder. */ public boolean isCreateDestinationFolder() { return createdestinationfolder; } /** * @return Returns the CreateTargetFolder. */ public boolean isCreateTargetFolder() { return createtargetfolder; } /** * @param createtargetfolderin * The createtargetfolder to set. */ public void setCreateTargetFolder( boolean createtargetfolderin ) { this.createtargetfolder = createtargetfolderin; } /** * @param publickey * The publicpublickey to set. */ public void setUsePublicKey( boolean publickey ) { this.publicpublickey = publickey; } /** * @return Returns the usehttpproxy. */ public boolean isUsePublicKey() { return publicpublickey; } public String getServerPort() { return serverPort; } public void setServerPort( String serverPort ) { this.serverPort = serverPort; } public void setHTTPProxyPort( String proxyport ) { this.httpproxyport = proxyport; } public String getHTTPProxyPort() { return httpproxyport; } public void setDestinationFolder( String destinationfolderin ) { this.destinationfolder = destinationfolderin; } public String getDestinationFolder() { return destinationfolder; } /** * @param timeout * The timeout to set. */ public void setTimeout( int timeout ) { this.timeout = timeout; } /** * @return Returns the timeout. */ public int getTimeout() { return timeout; } public Result execute( Result previousResult, int nr ) { Result result = previousResult; result.setResult( false ); if ( log.isRowLevel() ) { logRowlevel( BaseMessages.getString( PKG, "JobSSH2GET.Log.GettingFieldsValue" ) ); } // Get real variable value String realServerName = environmentSubstitute( serverName ); int realServerPort = Const.toInt( environmentSubstitute( serverPort ), 22 ); String realUserName = environmentSubstitute( userName ); String realServerPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( password ) ); // Proxy Host String realProxyHost = environmentSubstitute( httpProxyHost ); int realProxyPort = Const.toInt( environmentSubstitute( httpproxyport ), 22 ); String realproxyUserName = environmentSubstitute( httpproxyusername ); String realProxyPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( httpProxyPassword ) ); // Key file String realKeyFilename = environmentSubstitute( keyFilename ); String relKeyFilepass = environmentSubstitute( keyFilePass ); // target files String realLocalDirectory = environmentSubstitute( localDirectory ); String realwildcard = environmentSubstitute( wildcard ); // Remote source String realftpDirectory = environmentSubstitute( ftpDirectory ); // Destination folder (Move to) String realDestinationFolder = environmentSubstitute( destinationfolder ); try { // Remote source realftpDirectory = FTPUtils.normalizePath( realftpDirectory ); // Destination folder (Move to) realDestinationFolder = FTPUtils.normalizePath( realDestinationFolder ); } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.CanNotNormalizePath", e.getMessage() ) ); result.setNrErrors( 1 ); return result; } // Check for mandatory fields if ( log.isRowLevel() ) { logRowlevel( BaseMessages.getString( PKG, "JobSSH2GET.Log.CheckingMandatoryFields" ) ); } boolean mandatoryok = true; if ( Const.isEmpty( realServerName ) ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.ServernameMissing" ) ); } if ( usehttpproxy ) { if ( Const.isEmpty( realProxyHost ) ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.HttpProxyhostMissing" ) ); } } if ( publicpublickey ) { if ( Const.isEmpty( realKeyFilename ) ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.KeyFileMissing" ) ); } else { // Let's check if key file exists... if ( !new File( realKeyFilename ).exists() ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.KeyFileNotExist" ) ); } } } if ( Const.isEmpty( realLocalDirectory ) ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.LocalFolderMissing" ) ); } else { // Check if target folder exists... if ( !new File( realLocalDirectory ).exists() ) { if ( createtargetfolder ) { // Create Target folder if ( !CreateFolder( realLocalDirectory ) ) { mandatoryok = false; } } else { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.LocalFolderNotExists", realLocalDirectory ) ); } } else { if ( !new File( realLocalDirectory ).isDirectory() ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.LocalFolderNotFolder", realLocalDirectory ) ); } } } if ( afterFtpPut.equals( "move_file" ) ) { if ( Const.isEmpty( realDestinationFolder ) ) { mandatoryok = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.DestinatFolderMissing" ) ); } } if ( mandatoryok ) { Connection conn = null; SFTPv3Client client = null; boolean good = true; try { // Create a connection instance conn = getConnection( realServerName, realServerPort, realProxyHost, realProxyPort, realproxyUserName, realProxyPassword ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.ConnectionInstanceCreated" ) ); } if ( timeout > 0 ) { // Use timeout // Cache Host Key if ( cachehostkey ) { conn.connect( new SimpleVerifier( database ), 0, timeout * 1000 ); } else { conn.connect( null, 0, timeout * 1000 ); } } else { // Cache Host Key if ( cachehostkey ) { conn.connect( new SimpleVerifier( database ) ); } else { conn.connect(); } } // Authenticate boolean isAuthenticated = false; if ( publicpublickey ) { isAuthenticated = conn.authenticateWithPublicKey( realUserName, new File( realKeyFilename ), relKeyFilepass ); } else { isAuthenticated = conn.authenticateWithPassword( realUserName, realServerPassword ); } // LET'S CHECK AUTHENTICATION ... if ( isAuthenticated == false ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.AuthenticationFailed" ) ); } else { if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "JobSSH2GET.Log.Connected", serverName, userName ) ); } client = new SFTPv3Client( conn ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.ProtocolVersion", "" + client.getProtocolVersion() ) ); } // Check if ftp (source) directory exists if ( !Const.isEmpty( realftpDirectory ) ) { if ( !sshDirectoryExists( client, realftpDirectory ) ) { good = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.RemoteDirectoryNotExist", realftpDirectory ) ); } else if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.RemoteDirectoryExist", realftpDirectory ) ); } } if ( realDestinationFolder != null ) { // Check now destination folder if ( !sshDirectoryExists( client, realDestinationFolder ) ) { if ( createdestinationfolder ) { if ( !CreateRemoteFolder( client, realDestinationFolder ) ) { good = false; } } else { good = false; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.DestinatFolderNotExist", realDestinationFolder ) ); } } } if ( good ) { Pattern pattern = null; if ( !Const.isEmpty( realwildcard ) ) { pattern = Pattern.compile( realwildcard ); } if ( includeSubFolders ) { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.RecursiveModeOn" ) ); } copyRecursive( realftpDirectory, realLocalDirectory, client, pattern, parentJob ); } else { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.RecursiveModeOff" ) ); } GetFiles( realftpDirectory, realLocalDirectory, client, pattern, parentJob ); } /******************************** RESULT ********************/ if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.Result.JobEntryEnd1" ) ); logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.Result.TotalFiles", "" + nbfilestoget ) ); logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.Result.TotalFilesPut", "" + nbgot ) ); logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.Result.TotalFilesError", "" + nbrerror ) ); logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.Result.JobEntryEnd2" ) ); } if ( nbrerror == 0 ) { result.setResult( true ); /******************************** RESULT ********************/ } } } } catch ( Exception e ) { result.setNrErrors( nbrerror ); logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.ErrorFTP", e.getMessage() ) ); } finally { if ( conn != null ) { conn.close(); } if ( client != null ) { client.close(); } } } return result; } private Connection getConnection( String servername, int serverport, String proxyhost, int proxyport, String proxyusername, String proxypassword ) { /* Create a connection instance */ Connection conn = new Connection( servername, serverport ); /* We want to connect through a HTTP proxy */ if ( usehttpproxy ) { conn.setProxyData( new HTTPProxyData( proxyhost, proxyport ) ); /* Now connect */ // if the proxy requires basic authentication: if ( useBasicAuthentication ) { conn.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) ); } } return conn; } /** * Check existence of a file * * @param sftpClient * @param filename * @return true, if file exists * @throws Exception */ public boolean sshFileExists( SFTPv3Client sftpClient, String filename ) { try { SFTPv3FileAttributes attributes = sftpClient.stat( filename ); if ( attributes != null ) { return ( attributes.isRegularFile() ); } else { return false; } } catch ( Exception e ) { return false; } } /** * Check existence of a local file * * @param filename * @return true, if file exists */ public boolean FileExists( String filename ) { FileObject file = null; try { file = KettleVFS.getFileObject( filename, this ); if ( !file.exists() ) { return false; } else { if ( file.getType() == FileType.FILE ) { return true; } else { return false; } } } catch ( Exception e ) { return false; } } /** * Checks if file is a directory * * @param sftpClient * @param filename * @return true, if filename is a directory */ public boolean isDirectory( SFTPv3Client sftpClient, String filename ) { try { return sftpClient.stat( filename ).isDirectory(); } catch ( Exception e ) { // Ignore errors } return false; } /** * Checks if a directory exists * * @param sftpClient * @param directory * @return true, if directory exists */ public boolean sshDirectoryExists( SFTPv3Client sftpClient, String directory ) { try { SFTPv3FileAttributes attributes = sftpClient.stat( directory ); if ( attributes != null ) { return ( attributes.isDirectory() ); } else { return false; } } catch ( Exception e ) { return false; } } /** * Returns the file size of a file * * @param sftpClient * @param filename * @return the size of the file * @throws Exception */ public long getFileSize( SFTPv3Client sftpClient, String filename ) throws Exception { return sftpClient.stat( filename ).size.longValue(); } /********************************************************** * * @param selectedfile * @param wildcard * @param pattern * @return True if the selectedfile matches the wildcard **********************************************************/ private boolean getFileWildcard( String selectedfile, Pattern pattern ) { boolean getIt = true; // First see if the file matches the regular expression! if ( pattern != null ) { Matcher matcher = pattern.matcher( selectedfile ); getIt = matcher.matches(); } return getIt; } private boolean deleteOrMoveFiles( SFTPv3Client sftpClient, String filename, String destinationFolder ) { boolean retval = false; // Delete the file if this is needed! if ( afterFtpPut.equals( "delete_file" ) ) { try { sftpClient.rm( filename ); retval = true; if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.DeletedFile", filename ) ); } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.CanNotDeleteRemoteFile", filename ), e ); } } else if ( afterFtpPut.equals( "move_file" ) ) { String DestinationFullFilename = destinationFolder + Const.FILE_SEPARATOR + filename; try { sftpClient.mv( filename, DestinationFullFilename ); retval = true; if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.DeletedFile", filename ) ); } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.MovedFile", filename, destinationFolder ), e ); } } return retval; } /** * copy a directory from the remote host to the local one. * * @param sourceLocation * the source directory on the remote host * @param targetLocation * the target directory on the local host * @param sftpClient * is an instance of SFTPv3Client that makes SFTP client connection over SSH-2 * @return the number of files successfully copied * @throws Exception */ @SuppressWarnings( "unchecked" ) private void GetFiles( String sourceLocation, String targetLocation, SFTPv3Client sftpClient, Pattern pattern, Job parentJob ) throws Exception { String sourceFolder = "."; if ( !Const.isEmpty( sourceLocation ) ) { sourceFolder = sourceLocation + FTPUtils.FILE_SEPARATOR; } else { sourceFolder += FTPUtils.FILE_SEPARATOR; } Vector<SFTPv3DirectoryEntry> filelist = sftpClient.ls( sourceFolder ); if ( filelist != null ) { Iterator<SFTPv3DirectoryEntry> iterator = filelist.iterator(); while ( iterator.hasNext() && !parentJob.isStopped() ) { SFTPv3DirectoryEntry dirEntry = iterator.next(); if ( dirEntry == null ) { continue; } if ( dirEntry.filename.equals( "." ) || dirEntry.filename.equals( ".." ) || isDirectory( sftpClient, sourceFolder + dirEntry.filename ) ) { continue; } if ( getFileWildcard( dirEntry.filename, pattern ) ) { // Copy file from remote host copyFile( sourceFolder + dirEntry.filename, targetLocation + FTPUtils.FILE_SEPARATOR + dirEntry.filename, sftpClient ); } } } } /** * copy a directory from the remote host to the local one recursivly. * * @param sourceLocation * the source directory on the remote host * @param targetLocation * the target directory on the local host * @param sftpClient * is an instance of SFTPv3Client that makes SFTP client connection over SSH-2 * @return the number of files successfully copied * @throws Exception */ private void copyRecursive( String sourceLocation, String targetLocation, SFTPv3Client sftpClient, Pattern pattern, Job parentJob ) throws Exception { String sourceFolder = "." + FTPUtils.FILE_SEPARATOR; if ( sourceLocation != null ) { sourceFolder = sourceLocation; } if ( this.isDirectory( sftpClient, sourceFolder ) ) { Vector<?> filelist = sftpClient.ls( sourceFolder ); Iterator<?> iterator = filelist.iterator(); while ( iterator.hasNext() ) { SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry) iterator.next(); if ( dirEntry == null ) { continue; } if ( dirEntry.filename.equals( "." ) || dirEntry.filename.equals( ".." ) ) { continue; } copyRecursive( sourceFolder + FTPUtils.FILE_SEPARATOR + dirEntry.filename, targetLocation + Const.FILE_SEPARATOR + dirEntry.filename, sftpClient, pattern, parentJob ); } } else if ( isFile( sftpClient, sourceFolder ) ) { if ( getFileWildcard( sourceFolder, pattern ) ) { copyFile( sourceFolder, targetLocation, sftpClient ); } } } /** * Checks if file is a file * * @param sftpClient * @param filename * @return true, if filename is a directory */ public boolean isFile( SFTPv3Client sftpClient, String filename ) { try { return sftpClient.stat( filename ).isRegularFile(); } catch ( Exception e ) { // Ignore errors } return false; } /** * * @param sourceLocation * @param targetLocation * @param sftpClient * @return */ private void copyFile( String sourceLocation, String targetLocation, SFTPv3Client sftpClient ) { SFTPv3FileHandle sftpFileHandle = null; FileOutputStream fos = null; File transferFile = null; long remoteFileSize = -1; boolean filecopied = true; try { transferFile = new File( targetLocation ); if ( ( onlyGettingNewFiles == false ) || ( onlyGettingNewFiles == true ) && !FileExists( transferFile.getAbsolutePath() ) ) { new File( transferFile.getParent() ).mkdirs(); remoteFileSize = this.getFileSize( sftpClient, sourceLocation ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.ReceivingFile", sourceLocation, transferFile .getAbsolutePath(), "" + remoteFileSize ) ); } sftpFileHandle = sftpClient.openFileRO( sourceLocation ); fos = null; long offset = 0; fos = new FileOutputStream( transferFile ); byte[] buffer = new byte[2048]; while ( true ) { int len = sftpClient.read( sftpFileHandle, offset, buffer, 0, buffer.length ); if ( len <= 0 ) { break; } fos.write( buffer, 0, len ); offset += len; } fos.flush(); fos.close(); fos = null; nbfilestoget++; if ( remoteFileSize > 0 && remoteFileSize != transferFile.length() ) { filecopied = false; nbrerror++; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.RemoteFileLocalDifferent", "" + remoteFileSize, transferFile.length() + "", "" + offset ) ); } else { nbgot++; if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.RemoteFileLocalCopied", sourceLocation, transferFile + "" ) ); } } } // Let's now delete or move file if needed... if ( filecopied && !afterFtpPut.equals( "do_nothing" ) ) { deleteOrMoveFiles( sftpClient, sourceLocation, environmentSubstitute( destinationfolder ) ); } } catch ( Exception e ) { nbrerror++; logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.WritingFile", transferFile.getAbsolutePath(), e .getMessage() ) ); } finally { try { if ( sftpFileHandle != null ) { sftpClient.closeFile( sftpFileHandle ); sftpFileHandle = null; } if ( fos != null ) { try { fos.close(); fos = null; } catch ( Exception ex ) { // Ignore errors } } } catch ( Exception e ) { // Ignore errors } } } private boolean CreateFolder( String filefolder ) { FileObject folder = null; try { folder = KettleVFS.getFileObject( filefolder, this ); if ( !folder.exists() ) { if ( createtargetfolder ) { folder.createFolder(); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.FolderCreated", folder.toString() ) ); } } else { return false; } } return true; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.CanNotCreateFolder", folder.toString() ), e ); } finally { if ( folder != null ) { try { folder.close(); } catch ( Exception ex ) { /* Ignore */ } } } return false; } /** * Create remote folder * * @param sftpClient * @param foldername * @return true, if foldername is created */ private boolean CreateRemoteFolder( SFTPv3Client sftpClient, String foldername ) { boolean retval = false; if ( !sshDirectoryExists( sftpClient, foldername ) ) { try { sftpClient.mkdir( foldername, 0700 ); retval = true; if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobSSH2GET.Log.RemoteFolderCreated", foldername ) ); } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobSSH2GET.Log.Error.CreatingRemoteFolder", foldername ), e ); } } return retval; } public boolean evaluates() { return true; } public List<ResourceReference> getResourceDependencies( JobMeta jobMeta ) { List<ResourceReference> references = super.getResourceDependencies( jobMeta ); if ( !Const.isEmpty( serverName ) ) { String realServerName = jobMeta.environmentSubstitute( serverName ); ResourceReference reference = new ResourceReference( this ); reference.getEntries().add( new ResourceEntry( realServerName, ResourceType.SERVER ) ); references.add( reference ); } return references; } @Override public void check( List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space, Repository repository, IMetaStore metaStore ) { andValidator().validate( this, "serverName", remarks, putValidators( notBlankValidator() ) ); andValidator().validate( this, "localDirectory", remarks, putValidators( notBlankValidator(), fileExistsValidator() ) ); andValidator().validate( this, "userName", remarks, putValidators( notBlankValidator() ) ); andValidator().validate( this, "password", remarks, putValidators( notNullValidator() ) ); andValidator().validate( this, "serverPort", remarks, putValidators( integerValidator() ) ); } }
1.140625
1
retro/throttling/src/main/java/edu/brown/cs/systems/retro/throttling/ratelimiters/WrappedGoogleRateLimiter.java
forivall-mirrors/tracing-framework
82
17
package edu.brown.cs.systems.retro.throttling.ratelimiters; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Small extension to google rate limiter using a fair lock It ensures that when * the rate is updated, at most one request observes the old rate. With google's * rate limiter, requests observe the rate from when they were enqueued, so * there is lag. * * @author a-jomace * */ public class WrappedGoogleRateLimiter { // Fair lock - provides ordering private Lock lock = new ReentrantLock(true); private final com.google.common.util.concurrent.RateLimiter r; public WrappedGoogleRateLimiter() { this(Double.MAX_VALUE); } public WrappedGoogleRateLimiter(double permitsPerSecond) { this.r = com.google.common.util.concurrent.RateLimiter.create(permitsPerSecond); } public void setRate(double permitsPerSecond) { this.r.setRate(permitsPerSecond); } public boolean tryAcquire() { return tryAcquire(1); } public boolean tryAcquire(int permits) { if (!lock.tryLock()) return false; try { return this.r.tryAcquire(permits); } finally { lock.unlock(); } } public double acquire() { return acquire(1); } public double acquire(int permits) { lock.lock(); try { return this.r.acquire(permits); } finally { lock.unlock(); } } }
1.695313
2
snow-common/src/main/java/com/stylesmile/common/util/ReturnCode.java
stylesmile/snow
4
25
package com.stylesmile.common.util; /** * 数据返回码 * 0 : 成功 * @author : chenye */ public enum ReturnCode { NOT_LOGIN("401","未登录"), SUCCESS ("200","成功"), FAIL ("500","内部失败"), ACCESS_ERROR ("403","禁止访问"), NOT_FOUND ("404","页面未发现"); private String code; private String desc; ReturnCode(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
0.933594
1
com/planet_ink/coffee_mud/Abilities/Druid/Chant_PoisonousVine.java
random-mud-pie/CoffeeMud
1
33
package com.planet_ink.coffee_mud.Abilities.Druid; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2019 <NAME> 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. */ public class Chant_PoisonousVine extends Chant_SummonVine { @Override public String ID() { return "Chant_PoisonousVine"; } private final static String localizedName = CMLib.lang().L("Poisonous Vine"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Poisonous Vine)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int classificationCode() { return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTCONTROL; } @Override public int abstractQuality() { return Ability.QUALITY_BENEFICIAL_SELF; } @Override public int enchantQuality() { return Ability.QUALITY_INDIFFERENT; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override protected int canTargetCode() { return 0; } @Override public MOB determineMonster(final MOB caster, final int material) { final MOB victim=caster.getVictim(); final MOB newMOB=CMClass.getMOB("GenMOB"); int level=adjustedLevel(caster,0); if(level<1) level=1; newMOB.basePhyStats().setLevel(level); newMOB.basePhyStats().setAbility(13); newMOB.baseCharStats().setMyRace(CMClass.getRace("Vine")); final String name="a poisonous vine"; newMOB.setName(name); newMOB.setDisplayText(L("@x1 looks enraged!",name)); newMOB.setDescription(""); CMLib.factions().setAlignment(newMOB,Faction.Align.NEUTRAL); Ability A=CMClass.getAbility("Fighter_Rescue"); A.setProficiency(100); newMOB.addAbility(A); A=null; final int classlevel=CMLib.ableMapper().qualifyingClassLevel(caster,this)-CMLib.ableMapper().qualifyingLevel(caster,this); switch(classlevel/5) { case 0: A = CMClass.getAbility("Poison_Sting"); break; case 1: A = CMClass.getAbility("Poison_Bloodboil"); break; case 2: A = CMClass.getAbility("Poison_Venom"); break; default: A=CMClass.getAbility("Poison_Decreptifier"); break; } if(A!=null) { A.setProficiency(100); newMOB.addAbility(A); } newMOB.addBehavior(CMClass.getBehavior("CombatAbilities")); newMOB.setVictim(victim); newMOB.basePhyStats().setSensesMask(newMOB.basePhyStats().sensesMask()|PhyStats.CAN_SEE_DARK); newMOB.setLocation(caster.location()); newMOB.basePhyStats().setRejuv(PhyStats.NO_REJUV); newMOB.basePhyStats().setDamage(6+(5*(level/5))); newMOB.basePhyStats().setAttackAdjustment(10); newMOB.basePhyStats().setArmor(100-(30+(level/2))); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'N'); newMOB.addNonUninvokableEffect(CMClass.getAbility("Prop_ModExperience")); newMOB.setMiscText(newMOB.text()); newMOB.recoverCharStats(); newMOB.recoverPhyStats(); newMOB.recoverMaxState(); newMOB.resetToMaxState(); newMOB.bringToLife(caster.location(),true); CMLib.beanCounter().clearZeroMoney(newMOB,null); newMOB.setMoneyVariation(0); newMOB.setStartRoom(null); // keep before postFollow for Conquest CMLib.commands().postFollow(newMOB,caster,true); if(newMOB.amFollowing()!=caster) caster.tell(L("@x1 seems unwilling to follow you.",newMOB.name())); else { if(newMOB.getVictim()!=victim) newMOB.setVictim(victim); newMOB.location().showOthers(newMOB,victim,CMMsg.MSG_OK_ACTION,L("<S-NAME> start(s) attacking <T-NAMESELF>!")); } return(newMOB); } }
1.179688
1
wisdomSite/src/main/java/com/jlkj/common/exception/file/InvalidExtensionException.java
guodingfang/RuoYi-Vue
1
41
package com.jlkj.common.exception.file; import java.util.Arrays; import org.apache.commons.fileupload.FileUploadException; /** * 文件上传 误异常类 * * @author jlkj */ public class InvalidExtensionException extends FileUploadException { private static final long serialVersionUID = 1L; private String[] allowedExtension; private String extension; private String filename; public InvalidExtensionException(String[] allowedExtension, String extension, String filename) { super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); this.allowedExtension = allowedExtension; this.extension = extension; this.filename = filename; } public String[] getAllowedExtension() { return allowedExtension; } public String getExtension() { return extension; } public String getFilename() { return filename; } public static class InvalidImageExtensionException extends InvalidExtensionException { private static final long serialVersionUID = 1L; public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) { super(allowedExtension, extension, filename); } } public static class InvalidFlashExtensionException extends InvalidExtensionException { private static final long serialVersionUID = 1L; public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) { super(allowedExtension, extension, filename); } } public static class InvalidMediaExtensionException extends InvalidExtensionException { private static final long serialVersionUID = 1L; public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) { super(allowedExtension, extension, filename); } } }
1.273438
1
sabot/kernel/src/main/java/com/dremio/exec/expr/fn/impl/DecimalFunctions.java
techfoxy/dremio-oss
0
49
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.expr.fn.impl; import java.math.BigDecimal; import javax.inject.Inject; import org.apache.arrow.vector.holders.BigIntHolder; import org.apache.arrow.vector.holders.BitHolder; import org.apache.arrow.vector.holders.DecimalHolder; import org.apache.arrow.vector.holders.Float4Holder; import org.apache.arrow.vector.holders.Float8Holder; import org.apache.arrow.vector.holders.IntHolder; import org.apache.arrow.vector.holders.NullableBigIntHolder; import org.apache.arrow.vector.holders.NullableDecimalHolder; import org.apache.arrow.vector.holders.NullableFloat8Holder; import org.apache.arrow.vector.holders.NullableIntHolder; import org.apache.arrow.vector.holders.NullableVarCharHolder; import org.apache.arrow.vector.holders.VarCharHolder; import com.dremio.exec.expr.AggrFunction; import com.dremio.exec.expr.SimpleFunction; import com.dremio.exec.expr.annotations.FunctionTemplate; import com.dremio.exec.expr.annotations.FunctionTemplate.FunctionScope; import com.dremio.exec.expr.annotations.FunctionTemplate.NullHandling; import com.dremio.exec.expr.annotations.Output; import com.dremio.exec.expr.annotations.Param; import com.dremio.exec.expr.annotations.Workspace; import com.dremio.exec.expr.fn.FunctionErrorContext; import com.dremio.exec.expr.fn.FunctionGenerationHelper; import com.dremio.exec.expr.fn.OutputDerivation; import io.netty.buffer.ArrowBuf; public class DecimalFunctions { public static final String DECIMAL_CAST_NULL_ON_OVERFLOW = "castDECIMALNullOnOverflow"; @SuppressWarnings("unused") @FunctionTemplate(names = {"castVARCHAR"}, scope = FunctionScope.SIMPLE, nulls= NullHandling.NULL_IF_NULL) public static class CastDecimalVarChar implements SimpleFunction { @Param DecimalHolder in; @Param BigIntHolder len; @Output VarCharHolder out; @Inject ArrowBuf buffer; @Override public void setup() { } @Override public void eval() { in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); String istr = bd.toString(); out.start = 0; out.end = Math.min((int)len.value, istr.length()); // truncate if target type has length smaller than that of input's string buffer = buffer.reallocIfNeeded(out.end); out.buffer = buffer; out.buffer.setBytes(0, istr.substring(0,out.end).getBytes()); } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castFLOAT8"}, scope = FunctionScope.SIMPLE, nulls= NullHandling.NULL_IF_NULL) public static class CastDecimalFloat8 implements SimpleFunction { @Param DecimalHolder in; @Output Float8Holder out; @Override public void setup() { } @Override public void eval() { in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); out.value = bd.doubleValue(); } } public static void main(String[] args) { BigDecimal bd = new BigDecimal("99.0000"); System.out.println(bd.toString()); } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.NULL_IF_NULL) public static class CastVarCharDecimal implements SimpleFunction { @Param VarCharHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { String s = com.dremio.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(in.start, in.end, in.buffer); java.math.BigDecimal bd = new java.math.BigDecimal(s).setScale((int) scale.value, java.math.RoundingMode.HALF_UP); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(bd, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(names = {DECIMAL_CAST_NULL_ON_OVERFLOW}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.INTERNAL) public static class CastVarcharDecimalNullOnOverflow implements SimpleFunction { @Param NullableVarCharHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Workspace IntHolder expectedSignificantDigits; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); expectedSignificantDigits.value = (int)(precision.value - scale.value); } @Override public void eval() { out.isSet = in.isSet; if (in.isSet == 1) { String s = com.dremio.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(in.start, in.end, in.buffer); java.math.BigDecimal originalValue = new java.math.BigDecimal(s); java.math.BigDecimal convertedValue = originalValue.setScale((int) scale.value, java.math.RoundingMode .HALF_UP); int significantDigitsConverted = convertedValue.precision() - convertedValue.scale(); if (significantDigitsConverted > expectedSignificantDigits.value) { out.isSet = 0; } else { out.isSet = 1; try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(convertedValue, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } } } @SuppressWarnings("unused") @FunctionTemplate(names = {DECIMAL_CAST_NULL_ON_OVERFLOW}, derivation = OutputDerivation.DecimalCast .class, nulls= NullHandling.INTERNAL) public static class CastDecimalDecimalNullOnOverflow implements SimpleFunction { @Param NullableDecimalHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { out.isSet = in.isSet; if (in.isSet == 1) { int index = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, index, in.scale); java.math.BigDecimal result = input.setScale((int) scale.value, java.math.RoundingMode.HALF_UP); boolean overflow = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result, (int) precision.value); if (overflow) { out.isSet = 0; } else { out.isSet = 1; try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.NULL_IF_NULL) public static class CastDecimalDecimal implements SimpleFunction { @Param DecimalHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, index, in.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.roundWithPositiveScale(input, (int) scale.value, java.math.RoundingMode.HALF_UP); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.NULL_IF_NULL) public static class CastIntDecimal implements SimpleFunction { @Param IntHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { java.math.BigDecimal bd = java.math.BigDecimal.valueOf(in.value).setScale((int) scale.value, java.math.RoundingMode.HALF_UP); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(bd, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.NULL_IF_NULL) public static class CastBigIntDecimal implements SimpleFunction { @Param BigIntHolder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { java.math.BigDecimal bd = java.math.BigDecimal.valueOf(in.value).setScale((int) scale.value, java.math.RoundingMode.HALF_UP); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(bd, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class) public static class CastFloat4Decimal implements SimpleFunction { @Param Float4Holder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { out.isSet = 1; java.math.BigDecimal bd = java.math.BigDecimal.valueOf(in.value).setScale((int) scale.value, java.math.RoundingMode.HALF_UP); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(bd, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"castDECIMAL"}, derivation = OutputDerivation.DecimalCast.class, nulls= NullHandling.NULL_IF_NULL) public static class CastFloat8Decimal implements SimpleFunction { @Param Float8Holder in; @Param(constant = true) BigIntHolder precision; @Param(constant = true) BigIntHolder scale; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { java.math.BigDecimal bd = java.math.BigDecimal.valueOf(in.value).setScale((int) scale.value, java.math.RoundingMode.HALF_UP); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(bd, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; out.precision = (int) precision.value; out.scale = (int) scale.value; } } @SuppressWarnings("unused") @FunctionTemplate(name = "sum", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalSum implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableFloat8Holder sum; @Workspace NullableBigIntHolder nonNullCount; @Output NullableFloat8Holder out; public void setup() { sum = new NullableFloat8Holder(); sum.isSet = 1; sum.value = 0; nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; nonNullCount.value = 0; } public void add() { if (in.isSet != 0) { in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); sum.value += bd.doubleValue(); nonNullCount.value++; } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.value = sum.value; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { sum.value = 0; nonNullCount.value = 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "$sum0", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalSumZero implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableFloat8Holder sum; @Output NullableFloat8Holder out; public void setup() { sum = new NullableFloat8Holder(); sum.isSet = 1; sum.value = 0; } public void add() { if (in.isSet == 1) { in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); sum.value += bd.doubleValue(); } } public void output() { out.isSet = 1; out.value = sum.value; } public void reset() { sum.value = 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "min", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalMin implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableFloat8Holder minVal; @Workspace NullableBigIntHolder nonNullCount; @Output NullableFloat8Holder out; public void setup() { minVal = new NullableFloat8Holder(); minVal.isSet = 1; minVal.value = Double.MAX_VALUE; nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; nonNullCount.value = 0; } public void add() { if (in.isSet != 0) { nonNullCount.value = 1; in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); double val = bd.doubleValue(); if (val < minVal.value) { minVal.value = val; } } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.value = minVal.value; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { minVal.value = 0; nonNullCount.value = 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "max", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalMax implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableFloat8Holder maxVal; @Workspace NullableBigIntHolder nonNullCount; @Output NullableFloat8Holder out; public void setup() { maxVal = new NullableFloat8Holder(); maxVal.isSet = 1; maxVal.value = -Double.MAX_VALUE; nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; nonNullCount.value = 0; } public void add() { if (in.isSet != 0) { nonNullCount.value = 1; in.start = (in.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal bd = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in.buffer, in.start, in.scale); double val = bd.doubleValue(); if (val > maxVal.value) { maxVal.value = val; } } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.value = maxVal.value; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { maxVal.value = 0; nonNullCount.value = 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "sum_v2", derivation = OutputDerivation.DecimalAggSum.class, scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalSumV2 implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableDecimalHolder sum; @Workspace NullableBigIntHolder nonNullCount; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; public void setup() { sum = new NullableDecimalHolder(); sum.isSet = 1; buffer = buffer.reallocIfNeeded(16); sum.buffer = buffer; java.math.BigDecimal zero = new java.math.BigDecimal(java.math.BigInteger.ZERO, 0); org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(zero, sum.buffer, 0); sum.start = 0; nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; nonNullCount.value = 0; } public void add() { if (in.isSet == 1) { com.dremio.exec.util.DecimalUtils.addSignedDecimalInLittleEndianBytes(sum.buffer, sum.start, in.buffer, in .start, sum.buffer, sum.start); nonNullCount.value++; } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.buffer = sum.buffer; out.start = sum.start; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { nonNullCount.value = 0; java.math.BigDecimal zero = new java.math.BigDecimal(java.math.BigInteger.ZERO, 0); org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(zero, sum.buffer, 0); } } /** * Sum0 returns 0 instead of nulls in case all aggregation values * are null. */ @SuppressWarnings("unused") @FunctionTemplate(name = "$sum0_v2", derivation = OutputDerivation.DecimalAggSum.class, scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalSumZeroV2 implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableDecimalHolder sum; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; public void setup() { sum = new NullableDecimalHolder(); sum.isSet = 1; buffer = buffer.reallocIfNeeded(16); sum.buffer = buffer; sum.start = 0; java.math.BigDecimal zero = new java.math.BigDecimal(java.math.BigInteger.ZERO, 0); org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(zero, sum.buffer, 0); } public void add() { if (in.isSet == 1) { com.dremio.exec.util.DecimalUtils.addSignedDecimalInLittleEndianBytes(sum.buffer, sum.start, in.buffer, in .start, sum.buffer, sum.start); } } public void output() { out.isSet = 1; out.buffer = sum.buffer; out.start = sum.start; } public void reset() { java.math.BigDecimal zero = new java.math.BigDecimal(java.math.BigInteger.ZERO, 0); org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(zero, sum.buffer, 0); } } @SuppressWarnings("unused") @FunctionTemplate(name = "min_v2", derivation = OutputDerivation.DecimalAggMinMax.class, scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalMinV2 implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableDecimalHolder minVal; @Workspace NullableBigIntHolder nonNullCount; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; public void setup() { minVal = new NullableDecimalHolder(); minVal.isSet = 1; minVal.start = 0; buffer = buffer.reallocIfNeeded(16); minVal.buffer = buffer; nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(com.dremio.exec.util.DecimalUtils.MAX_DECIMAL, minVal.buffer, 0); nonNullCount.value = 0; } public void add() { if (in.isSet != 0) { nonNullCount.value = 1; int compare = com.dremio.exec.util.DecimalUtils .compareSignedDecimalInLittleEndianBytes(in.buffer, in.start, minVal.buffer, 0); if (compare < 0) { in.buffer.getBytes(in.start, minVal.buffer, 0 , org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH); } } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.buffer = minVal.buffer; out.start = 0; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(com.dremio.exec.util.DecimalUtils.MAX_DECIMAL, minVal.buffer, 0); nonNullCount.value = 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "max_v2", derivation = OutputDerivation.DecimalAggMinMax.class, scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE) public static class NullableDecimalMaxV2 implements AggrFunction { @Param NullableDecimalHolder in; @Workspace NullableDecimalHolder maxVal; @Workspace NullableBigIntHolder nonNullCount; @Output NullableDecimalHolder out; @Inject ArrowBuf buffer; public void setup() { maxVal = new NullableDecimalHolder(); maxVal.isSet = 1; maxVal.start = 0; buffer = buffer.reallocIfNeeded(16); maxVal.buffer = buffer; org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(com.dremio.exec.util.DecimalUtils.MIN_DECIMAL, maxVal.buffer, 0); nonNullCount = new NullableBigIntHolder(); nonNullCount.isSet = 1; nonNullCount.value = 0; } public void add() { if (in.isSet != 0) { nonNullCount.value = 1; int compare = com.dremio.exec.util.DecimalUtils .compareSignedDecimalInLittleEndianBytes(in.buffer, in.start, maxVal.buffer, 0); if (compare > 0) { in.buffer.getBytes(in.start, maxVal.buffer, 0 , org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH); } } } public void output() { if (nonNullCount.value > 0) { out.isSet = 1; out.buffer = maxVal.buffer; out.start = 0; } else { // All values were null. Result should be null too out.isSet = 0; } } public void reset() { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(com.dremio.exec.util.DecimalUtils.MIN_DECIMAL, maxVal.buffer, 0); nonNullCount.value = 0; } } /** * Decimal comparator where null appears last i.e. nulls are considered * larger than all values. */ @FunctionTemplate(name = FunctionGenerationHelper.COMPARE_TO_NULLS_HIGH, scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = NullHandling.INTERNAL) public static class CompareDecimalVsDecimalNullsHigh implements SimpleFunction { @Param NullableDecimalHolder left; @Param NullableDecimalHolder right; @Output NullableIntHolder out; public void setup() {} public void eval() { out.isSet = 1; outside: { if ( left.isSet == 0 ) { if ( right.isSet == 0 ) { out.value = 0; break outside; } else { out.value = 1; break outside; } } else if ( right.isSet == 0 ) { out.value = -1; break outside; } out.value = com.dremio.exec.util.DecimalUtils.compareSignedDecimalInLittleEndianBytes (left.buffer, left.start, right.buffer, right.start); } // outside } } /** * Decimal comparator where null appears first i.e. nulls are considered * smaller than all values. */ @FunctionTemplate(name = FunctionGenerationHelper.COMPARE_TO_NULLS_LOW, scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = NullHandling.INTERNAL) public static class CompareDecimalVsDecimalNullsLow implements SimpleFunction { @Param NullableDecimalHolder left; @Param NullableDecimalHolder right; @Output NullableIntHolder out; public void setup() {} public void eval() { out.isSet = 1; outside: { if ( left.isSet == 0 ) { if ( right.isSet == 0 ) { out.value = 0; break outside; } else { out.value = -1; break outside; } } else if ( right.isSet == 0 ) { out.value = 1; break outside; } out.value = com.dremio.exec.util.DecimalUtils.compareSignedDecimalInLittleEndianBytes (left.buffer, left.start, right.buffer, right.start); } // outside } } public static BigDecimal checkOverflow(BigDecimal in) { return in.precision() > 38 ? new BigDecimal(0) : in; } public static boolean checkOverflow(BigDecimal in, int precision) { return in.precision() > precision; } public static BigDecimal addOrSubtract(boolean isSubtract, BigDecimal left, BigDecimal right, int outPrecision, int outScale) { if (isSubtract) { right = right.negate(); } int higherScale = Math.max(left.scale(), right.scale()); // >= outScale BigDecimal leftScaled = left.setScale(higherScale, BigDecimal.ROUND_UNNECESSARY); BigDecimal rightScaled = right.setScale(higherScale, BigDecimal.ROUND_UNNECESSARY); BigDecimal result = leftScaled.add(rightScaled); if (higherScale > outScale) { result = result.setScale(outScale, BigDecimal.ROUND_HALF_UP); } return checkOverflow(result); } @SuppressWarnings("unused") @FunctionTemplate(name = "add", scope = FunctionScope.SIMPLE, derivation = OutputDerivation.DecimalAdd.class, nulls = NullHandling.NULL_IF_NULL) public static class AddTwoDecimals implements SimpleFunction { @Param DecimalHolder in1; @Param DecimalHolder in2; @Output DecimalHolder out; @Inject ArrowBuf buffer; @Inject FunctionErrorContext errorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (in1.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in1.buffer, index, in1.scale); index = (in2.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(in2.buffer, index, in2.scale); org.apache.arrow.vector.types.pojo.ArrowType.Decimal resultTypeForOperation = org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.getResultTypeForOperation(org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.OperationType.ADD, new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(in1.precision, in1.scale), new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(in2.precision, in2.scale)); out.precision = resultTypeForOperation.getPrecision(); out.scale = resultTypeForOperation.getScale(); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.addOrSubtract(false, left, right, out.precision, out.scale); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw errorContext.error(e) .build(); } out.buffer = buffer; } } @SuppressWarnings("unused") @FunctionTemplate(name = "subtract", scope = FunctionScope.SIMPLE, derivation = OutputDerivation.DecimalSubtract.class, nulls = NullHandling.NULL_IF_NULL) public static class SubtractDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); org.apache.arrow.vector.types.pojo.ArrowType.Decimal resultTypeForOperation = org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.getResultTypeForOperation(org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.OperationType.SUBTRACT, new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(leftHolder.precision, leftHolder.scale), new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(rightHolder.precision, rightHolder.scale)); resultHolder.precision = resultTypeForOperation.getPrecision(); resultHolder.scale = resultTypeForOperation.getScale(); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.addOrSubtract(true, left, right, resultHolder.precision, resultHolder.scale); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; } } @SuppressWarnings("unused") @FunctionTemplate(name = "multiply", derivation = OutputDerivation.DecimalMultiply.class, scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class MultiplyDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); org.apache.arrow.vector.types.pojo.ArrowType.Decimal resultTypeForOperation = org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.getResultTypeForOperation(org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.OperationType.MULTIPLY, new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(leftHolder.precision, leftHolder.scale), new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(rightHolder.precision, rightHolder.scale)); resultHolder.precision = resultTypeForOperation.getPrecision(); resultHolder.scale = resultTypeForOperation.getScale(); java.math.BigDecimal result = left.multiply(right).setScale(resultHolder.scale, java.math.BigDecimal.ROUND_HALF_UP); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; } } @SuppressWarnings("unused") @FunctionTemplate(name = "divide", derivation = OutputDerivation.DecimalDivide.class, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class DivideDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); org.apache.arrow.vector.types.pojo.ArrowType.Decimal resultTypeForOperation = org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.getResultTypeForOperation(org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.OperationType.DIVIDE, new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(leftHolder.precision, leftHolder.scale), new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(rightHolder.precision, rightHolder.scale)); resultHolder.precision = resultTypeForOperation.getPrecision(); resultHolder.scale = resultTypeForOperation.getScale(); if (resultHolder.scale > leftHolder.scale - rightHolder.scale) { left = left.setScale(resultHolder.scale + rightHolder.scale, java.math.BigDecimal.ROUND_UNNECESSARY); } java.math.BigInteger leftUnscaled = left.unscaledValue(); java.math.BigInteger rightUnscaled = right.unscaledValue(); java.math.BigInteger[] quotientAndRemainder = leftUnscaled.divideAndRemainder(rightUnscaled); java.math.BigInteger resultUnscaled = quotientAndRemainder[0]; if (quotientAndRemainder[1].abs().multiply(java.math.BigInteger.valueOf(2)).compareTo (rightUnscaled.abs()) >= 0) { resultUnscaled = resultUnscaled.add(java.math.BigInteger.valueOf((leftUnscaled.signum() ^ rightUnscaled.signum()) + 1)); } java.math.BigDecimal result = new java.math.BigDecimal(resultUnscaled, resultHolder.scale); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"modulo", "mod"}, derivation = OutputDerivation.DecimalMod.class, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class ModuloFunction implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); org.apache.arrow.vector.types.pojo.ArrowType.Decimal resultTypeForOperation = org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.getResultTypeForOperation(org.apache.arrow.gandiva.evaluator.DecimalTypeUtil.OperationType.MOD, new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(leftHolder.precision, leftHolder.scale), new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(rightHolder.precision, rightHolder.scale)); resultHolder.precision = resultTypeForOperation.getPrecision(); resultHolder.scale = resultTypeForOperation.getScale(); if (leftHolder.scale < rightHolder.scale) { left = left.setScale(rightHolder.scale, java.math.BigDecimal.ROUND_UNNECESSARY); } else { right = right.setScale(leftHolder.scale, java.math.BigDecimal.ROUND_UNNECESSARY); } java.math.BigInteger leftUnscaled = left.unscaledValue(); java.math.BigInteger rightUnscaled = right.unscaledValue(); java.math.BigInteger remainder = leftUnscaled.remainder(rightUnscaled); java.math.BigDecimal result = new java.math.BigDecimal(remainder, resultHolder.scale); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; } } @SuppressWarnings("unused") @FunctionTemplate(names = {"equal", "==", "="}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class EqualsDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) == 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate( names = {"not_equal", "<>", "!="}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class NotEqualsDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) != 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate( names = {"less_than", "<"}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class LessThanDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) < 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate( names = {"less_than_or_equal_to", "<="}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class LessThanEqDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) <= 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate( names = {"greater_than", ">"}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class GreaterThanDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) > 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate( names = {"greater_than_or_equal_to", ">="}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public static class GreaterThanEqDecimals implements SimpleFunction { @Param DecimalHolder leftHolder; @Param DecimalHolder rightHolder; @Output BitHolder resultHolder; @Override public void setup() { } @Override public void eval() { int index = (leftHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal left = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(leftHolder.buffer, index, leftHolder.scale); index = (rightHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal right = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(rightHolder.buffer, index, rightHolder.scale); resultHolder.value = (left.compareTo(right) >= 0) ? 1 : 0; } } @SuppressWarnings("unused") @FunctionTemplate(name = "abs", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalMax.class) public static class AbsDecimal implements SimpleFunction { @Param DecimalHolder inputHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = input.abs(); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; resultHolder.precision = inputHolder.precision; resultHolder.scale = inputHolder.scale; } } public static java.math.BigDecimal round(BigDecimal input, int scale, java.math.RoundingMode roundingMode) { if (scale < 0) { return com.dremio.exec.expr.fn.impl.DecimalFunctions.roundWithNegativeScale(input, scale, roundingMode); } return com.dremio.exec.expr.fn.impl.DecimalFunctions.roundWithPositiveScale(input, scale, roundingMode); } // scale is negative private static BigDecimal roundWithNegativeScale(BigDecimal input, int scale, java.math.RoundingMode roundingMode) { java.math.BigDecimal inputNoFractional = input.setScale(0, roundingMode); java.math.BigDecimal result = new java.math.BigDecimal(inputNoFractional.unscaledValue() .subtract(inputNoFractional.unscaledValue().remainder(java.math.BigInteger.TEN.pow(-scale))), scale); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); return result; } public static BigDecimal roundWithPositiveScale(BigDecimal input, int scale, java.math .RoundingMode roundingMode) { java.math.BigDecimal result = input.setScale(scale, roundingMode); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); return result; } @SuppressWarnings("unused") @FunctionTemplate(name = "round", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalSetScale.class) public static class RoundDecimalWithScale implements SimpleFunction { @Param DecimalHolder inputHolder; @Param(constant = true) IntHolder scale; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, scale.value, java.math.RoundingMode.HALF_UP); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_SET_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale), new com.dremio.common.expression.ValueExpressions.IntExpression(scale.value))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } @SuppressWarnings("unused") @FunctionTemplate(name = "round", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalZeroScale.class) public static class RoundDecimal implements SimpleFunction { @Param DecimalHolder inputHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, 0, java.math.RoundingMode.HALF_UP); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_ZERO_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } @SuppressWarnings("unused") @FunctionTemplate(names = {"truncate", "trunc"}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalSetScale.class) public static class TruncateDecimalWithScale implements SimpleFunction { @Param DecimalHolder inputHolder; @Param(constant = true) IntHolder scale; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, scale.value, java.math.RoundingMode.DOWN); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_SET_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale), new com.dremio.common.expression.ValueExpressions.IntExpression(scale.value))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } @SuppressWarnings("unused") @FunctionTemplate(names = {"truncate", "trunc"}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalZeroScale.class) public static class TruncateDecimal implements SimpleFunction { @Param DecimalHolder inputHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, 0, java.math.RoundingMode.DOWN); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_ZERO_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } @SuppressWarnings("unused") @FunctionTemplate(name = "ceil", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalZeroScale.class) public static class CeilDecimal implements SimpleFunction { @Param DecimalHolder inputHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, 0, java.math.RoundingMode.CEILING); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_ZERO_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } @SuppressWarnings("unused") @FunctionTemplate(name = "floor", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL, derivation = OutputDerivation.DecimalZeroScale.class) public static class FloorDecimal implements SimpleFunction { @Param DecimalHolder inputHolder; @Output DecimalHolder resultHolder; @Inject ArrowBuf buffer; @Inject FunctionErrorContext functionErrorContext; @Override public void setup() { buffer = buffer.reallocIfNeeded(16); } @Override public void eval() { int index = (inputHolder.start / (org.apache.arrow.vector.util.DecimalUtility.DECIMAL_BYTE_LENGTH)); java.math.BigDecimal input = org.apache.arrow.vector.util.DecimalUtility.getBigDecimalFromArrowBuf(inputHolder.buffer, index, inputHolder.scale); java.math.BigDecimal result = com.dremio.exec.expr.fn.impl.DecimalFunctions.round(input, 0, java.math.RoundingMode.FLOOR); result = com.dremio.exec.expr.fn.impl.DecimalFunctions.checkOverflow(result); try { org.apache.arrow.vector.util.DecimalUtility.writeBigDecimalToArrowBuf(result, buffer, 0); } catch (RuntimeException e) { throw functionErrorContext.error(e) .build(); } resultHolder.buffer = buffer; com.dremio.common.expression.CompleteType outputType = com.dremio.exec.expr.fn.OutputDerivation.DECIMAL_ZERO_SCALE.getOutputType( com.dremio.common.expression.CompleteType.DECIMAL, java.util.Arrays.asList( new com.dremio.common.expression.ValueExpressions.DecimalExpression(input, inputHolder.precision, inputHolder.scale))); resultHolder.scale = outputType.getScale(); resultHolder.precision = outputType.getPrecision(); } } }
1.195313
1
src/main/java/edu/javavt17Second/config/WebConfig.java
intusmortius/javavt17Second
0
57
package edu.javavt17Second.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.ResourceBundleViewResolver; @Configuration @ComponentScan({"edu.javavt17Second"}) @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver getViewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/pages/"); resolver.setSuffix(".jsp"); resolver.setOrder(2); return resolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); if (!registry.hasMappingForPattern("/webjars/**")) { registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } } }
1.054688
1
src/main/java/com/facebook/LinkBench/LinkBenchRequest.java
Jeffery-Song/linkbench
0
65
/* * Copyright 2012, Facebook, 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.facebook.LinkBench; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.facebook.LinkBench.RealDistribution.DistributionType; import com.facebook.LinkBench.distributions.AccessDistributions; import com.facebook.LinkBench.distributions.AccessDistributions.AccessDistribution; import com.facebook.LinkBench.distributions.ID2Chooser; import com.facebook.LinkBench.distributions.ID2ChooserBase; import com.facebook.LinkBench.distributions.AliID2Chooser; import com.facebook.LinkBench.distributions.LogNormalDistribution; import com.facebook.LinkBench.distributions.ProbabilityDistribution; import com.facebook.LinkBench.generators.DataGenerator; import com.facebook.LinkBench.stats.LatencyStats; import com.facebook.LinkBench.stats.SampledStats; import com.facebook.LinkBench.util.ClassLoadUtil; import com.facebook.LinkBench.measurements.Measurements; public class LinkBenchRequest implements Runnable { private static long start_time; // only for ali case. private static AtomicLong _nodeid; private final Logger logger = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER); Properties props; LinkStore linkStore; NodeStore nodeStore; RequestProgress progressTracker; boolean use_duration; int duration; long numRequests; /** Requests per second: <= 0 for unlimited rate */ private long requestrate; /** Maximum number of failed requests: < 0 for unlimited */ private long maxFailedRequests; /** * Time to run benchmark for before collecting stats. Allows * caches, etc to warm up. */ private long warmupTime; /** Maximum time to run benchmark for, not including warmup time */ long maxTime; int nrequesters; int requesterID; long maxid1; long startid1; Level debuglevel; long displayFreq_ms; long progressFreq_ms; String dbid; boolean singleAssoc = false; // Control data generation settings private LogNormalDistribution linkDataSize; private DataGenerator linkAddDataGen; private DataGenerator linkUpDataGen; private LogNormalDistribution nodeDataSize; private DataGenerator nodeAddDataGen; private DataGenerator nodeUpDataGen; // cummulative percentages double pc_addlink; double pc_deletelink; double pc_updatelink; double pc_countlink; double pc_getlink; double pc_getlinklist; double pc_addnode; double pc_deletenode; double pc_updatenode; double pc_getnode; double pc_ali_login; double pc_ali_reg; double pc_ali_pay; double pc_ali_get_fan; double pc_ali_get_follow; double pc_ali_recom; double pc_ali_follow; double pc_ali_unfollow; // Chance of doing historical range query double p_historical_getlinklist; boolean is_ali; private static class HistoryKey { public final long id1; public final long link_type; public HistoryKey(long id1, long link_type) { super(); this.id1 = id1; this.link_type = link_type; } public HistoryKey(Link l) { this(l.id1, l.link_type); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id1 ^ (id1 >>> 32)); result = prime * result + (int) (link_type ^ (link_type >>> 32)); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof HistoryKey)) return false; HistoryKey other = (HistoryKey) obj; return id1 == other.id1 && link_type == other.link_type; } } // Cache of last link in lists where full list wasn't retrieved ArrayList<Link> listTailHistory; // Index of history to avoid duplicates HashMap<HistoryKey, Integer> listTailHistoryIndex; // Limit of cache size private int listTailHistoryLimit; // Probability distribution for ids in multiget ProbabilityDistribution multigetDist; // Statistics SampledStats stats; LatencyStats latencyStats; // Other informational counters long numfound = 0; long numnotfound = 0; long numHistoryQueries = 0; Measurements _measurements; /** * Random number generator use for generating workload. If * initialized with same seed, should generate same sequence of requests * so that tests and benchmarks are repeatable. */ Random rng; // Last node id accessed long lastNodeId; long requestsDone = 0; long errors = 0; boolean aborted; // Access distributions private AccessDistribution writeDist; // link writes private AccessDistribution writeDistUncorr; // to blend with link writes private double writeDistUncorrBlend; // Percentage to used writeDist2 for private AccessDistribution readDist; // link reads private AccessDistribution readDistUncorr; // to blend with link reads private double readDistUncorrBlend; // Percentage to used readDist2 for private AccessDistribution nodeReadDist; // node reads private AccessDistribution nodeUpdateDist; // node writes private AccessDistribution nodeDeleteDist; // node deletes private ID2ChooserBase id2chooser; public LinkBenchRequest(LinkStore linkStore, NodeStore nodeStore, Properties props, LatencyStats latencyStats, PrintStream csvStreamOut, RequestProgress progressTracker, Random rng, int requesterID, int nrequesters) { assert(linkStore != null); if (requesterID < 0 || requesterID >= nrequesters) { throw new IllegalArgumentException("Bad requester id " + requesterID + "/" + nrequesters); } this.linkStore = linkStore; this.nodeStore = nodeStore; this.props = props; this.latencyStats = latencyStats; this.progressTracker = progressTracker; this.rng = rng; this.nrequesters = nrequesters; this.requesterID = requesterID; is_ali = ConfigUtil.getBool(props, "is_ali"); debuglevel = ConfigUtil.getDebugLevel(props); dbid = ConfigUtil.getPropertyRequired(props, Config.DBID); numRequests = ConfigUtil.getLong(props, Config.NUM_REQUESTS); use_duration = ConfigUtil.getBool(props, Config.USE_DURATION, true); duration = ConfigUtil.getInt(props, Config.DURATION, 30); requestrate = ConfigUtil.getLong(props, Config.REQUEST_RATE, 0L); maxFailedRequests = ConfigUtil.getLong(props, Config.MAX_FAILED_REQUESTS, 0L); warmupTime = Math.max(0, ConfigUtil.getLong(props, Config.WARMUP_TIME, 0L)); maxTime = ConfigUtil.getLong(props, Config.MAX_TIME); maxid1 = ConfigUtil.getLong(props, Config.MAX_ID); startid1 = ConfigUtil.getLong(props, Config.MIN_ID); // math functions may cause problems for id1 < 1 if (startid1 <= 0) { throw new LinkBenchConfigError("startid1 must be >= 1"); } if (maxid1 <= startid1) { throw new LinkBenchConfigError("maxid1 must be > startid1"); } // is this a single assoc test? if (startid1 + 1 == maxid1) { singleAssoc = true; logger.info("Testing single row assoc read."); } initRequestProbabilities(props); initLinkDataGeneration(props); initLinkRequestDistributions(props, requesterID, nrequesters); if (pc_getnode > pc_getlinklist) { // Load stuff for node workload if needed if (nodeStore == null) { throw new IllegalArgumentException("nodeStore not provided but non-zero " + "probability of node operation"); } initNodeDataGeneration(props); initNodeRequestDistributions(props); } displayFreq_ms = ConfigUtil.getLong(props, Config.DISPLAY_FREQ, 60L) * 1000; progressFreq_ms = ConfigUtil.getLong(props, Config.PROGRESS_FREQ, 6L) * 1000; int maxsamples = ConfigUtil.getInt(props, Config.MAX_STAT_SAMPLES); stats = new SampledStats(requesterID, maxsamples, csvStreamOut); listTailHistoryLimit = 2048; // Hardcoded limit for now listTailHistory = new ArrayList<Link>(listTailHistoryLimit); listTailHistoryIndex = new HashMap<HistoryKey, Integer>(); p_historical_getlinklist = ConfigUtil.getDouble(props, Config.PR_GETLINKLIST_HISTORY, 0.0) / 100; lastNodeId = startid1; _measurements=Measurements.getMeasurements(); synchronized(this.getClass()) { if (_nodeid == null) { _nodeid = new AtomicLong(maxid1); } } } private void initRequestProbabilities(Properties props) { pc_addlink = ConfigUtil.getDouble(props, Config.PR_ADD_LINK); pc_deletelink = pc_addlink + ConfigUtil.getDouble(props, Config.PR_DELETE_LINK); pc_updatelink = pc_deletelink + ConfigUtil.getDouble(props, Config.PR_UPDATE_LINK); pc_countlink = pc_updatelink + ConfigUtil.getDouble(props, Config.PR_COUNT_LINKS); pc_getlink = pc_countlink + ConfigUtil.getDouble(props, Config.PR_GET_LINK); pc_getlinklist = pc_getlink + ConfigUtil.getDouble(props, Config.PR_GET_LINK_LIST); pc_addnode = pc_getlinklist + ConfigUtil.getDouble(props, Config.PR_ADD_NODE, 0.0); pc_updatenode = pc_addnode + ConfigUtil.getDouble(props, Config.PR_UPDATE_NODE, 0.0); pc_deletenode = pc_updatenode + ConfigUtil.getDouble(props, Config.PR_DELETE_NODE, 0.0); pc_getnode = pc_deletenode + ConfigUtil.getDouble(props, Config.PR_GET_NODE, 0.0); pc_ali_login = pc_getnode + ConfigUtil.getDouble(props, Config.PR_ALI_LOGIN, 0.0); pc_ali_reg = pc_ali_login + ConfigUtil.getDouble(props, Config.PR_ALI_REG, 0.0); pc_ali_pay = pc_ali_reg + ConfigUtil.getDouble(props, Config.PR_ALI_PAY, 0.0); pc_ali_get_fan = pc_ali_pay + ConfigUtil.getDouble(props, Config.PR_ALI_GET_FAN, 0.0); pc_ali_get_follow = pc_ali_get_fan + ConfigUtil.getDouble(props, Config.PR_ALI_GET_FOLLOW, 0.0); pc_ali_recom = pc_ali_get_follow + ConfigUtil.getDouble(props, Config.PR_ALI_RECOM, 0.0); pc_ali_follow = pc_ali_recom + ConfigUtil.getDouble(props, Config.PR_ALI_FOLLOW, 0.0); pc_ali_unfollow = pc_ali_follow + ConfigUtil.getDouble(props, Config.PR_ALI_UNFOLLOW, 0.0); if (Math.abs(pc_ali_follow - 100.0) > 1e-5) {//compare real numbers throw new LinkBenchConfigError("Percentages of request types do not " + "add to 100, only " + pc_ali_follow + "!"); } } private void initLinkRequestDistributions(Properties props, int requesterID, int nrequesters) { writeDist = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.LINK_WRITES); readDist = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.LINK_READS); // Load uncorrelated distributions for blending if needed writeDistUncorr = null; if (props.containsKey(Config.WRITE_UNCORR_BLEND)) { // Ratio of queries to use uncorrelated. Convert from percentage writeDistUncorrBlend = ConfigUtil.getDouble(props, Config.WRITE_UNCORR_BLEND) / 100.0; if (writeDistUncorrBlend > 0.0) { writeDistUncorr = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.LINK_WRITES_UNCORR); } } readDistUncorr = null; if (props.containsKey(Config.READ_UNCORR_BLEND)) { // Ratio of queries to use uncorrelated. Convert from percentage readDistUncorrBlend = ConfigUtil.getDouble(props, Config.READ_UNCORR_BLEND) / 100.0; if (readDistUncorrBlend > 0.0) { readDistUncorr = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.LINK_READS_UNCORR); } } if (is_ali) { id2chooser = new AliID2Chooser(props, startid1, maxid1, nrequesters, requesterID); } else { id2chooser = new ID2Chooser(props, startid1, maxid1, nrequesters, requesterID); } // Distribution of #id2s per multiget String multigetDistClass = props.getProperty(Config.LINK_MULTIGET_DIST); if (multigetDistClass != null && multigetDistClass.trim().length() != 0) { int multigetMin = ConfigUtil.getInt(props, Config.LINK_MULTIGET_DIST_MIN); int multigetMax = ConfigUtil.getInt(props, Config.LINK_MULTIGET_DIST_MAX); try { multigetDist = ClassLoadUtil.newInstance(multigetDistClass, ProbabilityDistribution.class); multigetDist.init(multigetMin, multigetMax, props, Config.LINK_MULTIGET_DIST_PREFIX); } catch (ClassNotFoundException e) { logger.error(e); throw new LinkBenchConfigError("Class" + multigetDistClass + " could not be loaded as ProbabilityDistribution"); } } else { multigetDist = null; } } private void initLinkDataGeneration(Properties props) { try { double medLinkDataSize = ConfigUtil.getDouble(props, Config.LINK_DATASIZE); linkDataSize = new LogNormalDistribution(); linkDataSize.init(0, LinkStore.MAX_LINK_DATA, medLinkDataSize, Config.LINK_DATASIZE_SIGMA); linkAddDataGen = ClassLoadUtil.newInstance( ConfigUtil.getPropertyRequired(props, Config.LINK_ADD_DATAGEN), DataGenerator.class); linkAddDataGen.init(props, Config.LINK_ADD_DATAGEN_PREFIX); linkUpDataGen = ClassLoadUtil.newInstance( ConfigUtil.getPropertyRequired(props, Config.LINK_UP_DATAGEN), DataGenerator.class); linkUpDataGen.init(props, Config.LINK_UP_DATAGEN_PREFIX); } catch (ClassNotFoundException ex) { logger.error(ex); throw new LinkBenchConfigError("Error loading data generator class: " + ex.getMessage()); } } private void initNodeRequestDistributions(Properties props) { try { nodeReadDist = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.NODE_READS); } catch (LinkBenchConfigError e) { // Not defined logger.info("Node access distribution not configured: " + e.getMessage()); throw new LinkBenchConfigError("Node read distribution not " + "configured but node read operations have non-zero probability"); } try { nodeUpdateDist = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.NODE_UPDATES); } catch (LinkBenchConfigError e) { // Not defined logger.info("Node access distribution not configured: " + e.getMessage()); throw new LinkBenchConfigError("Node write distribution not " + "configured but node write operations have non-zero probability"); } try { nodeDeleteDist = AccessDistributions.loadAccessDistribution(props, startid1, maxid1, DistributionType.NODE_DELETES); } catch (LinkBenchConfigError e) { // Not defined logger.info("Node delete distribution not configured: " + e.getMessage()); throw new LinkBenchConfigError("Node delete distribution not " + "configured but node write operations have non-zero probability"); } } private void initNodeDataGeneration(Properties props) { try { double medNodeDataSize = ConfigUtil.getDouble(props, Config.NODE_DATASIZE); nodeDataSize = new LogNormalDistribution(); nodeDataSize.init(0, NodeStore.MAX_NODE_DATA, medNodeDataSize, Config.NODE_DATASIZE_SIGMA); String dataGenClass = ConfigUtil.getPropertyRequired(props, Config.NODE_ADD_DATAGEN); nodeAddDataGen = ClassLoadUtil.newInstance(dataGenClass, DataGenerator.class); nodeAddDataGen.init(props, Config.NODE_ADD_DATAGEN_PREFIX); dataGenClass = ConfigUtil.getPropertyRequired(props, Config.NODE_UP_DATAGEN); nodeUpDataGen = ClassLoadUtil.newInstance(dataGenClass, DataGenerator.class); nodeUpDataGen.init(props, Config.NODE_UP_DATAGEN_PREFIX); } catch (ClassNotFoundException ex) { logger.error(ex); throw new LinkBenchConfigError("Error loading data generator class: " + ex.getMessage()); } } public long getRequestsDone() { return requestsDone; } public boolean didAbort() { return aborted; } // gets id1 for the request based on desired distribution private long chooseRequestID(DistributionType type, long previousId1) { AccessDistribution dist; switch (type) { case LINK_READS: // Blend between distributions if needed if (readDistUncorr == null || rng.nextDouble() >= readDistUncorrBlend) { dist = readDist; } else { dist = readDistUncorr; } break; case LINK_WRITES: // Blend between distributions if needed if (writeDistUncorr == null || rng.nextDouble() >= writeDistUncorrBlend) { dist = writeDist; } else { dist = writeDistUncorr; } break; case LINK_WRITES_UNCORR: dist = writeDistUncorr; break; case NODE_READS: dist = nodeReadDist; break; case NODE_UPDATES: dist = nodeUpdateDist; break; case NODE_DELETES: dist = nodeDeleteDist; break; default: throw new RuntimeException("Unknown value for type: " + type); } long newid1 = dist.nextID(rng, previousId1); // Distribution responsible for generating number in range assert((newid1 >= startid1) && (newid1 < maxid1)); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("id1 generated = " + newid1 + " for access distribution: " + dist.getClass().getName() + ": " + dist.toString()); } if (dist.getShuffler() != null) { // Shuffle to go from position in space ranked from most to least accessed, // to the real id space newid1 = startid1 + dist.getShuffler().permute(newid1 - startid1); } return newid1; } /** * Randomly choose a single request and execute it, updating statistics * @param recordStats If true, record latency and other stats. * @return true if successful, false on error */ private boolean oneRequest(boolean recordStats) { double r = rng.nextDouble() * 100.0; long starttime = 0; long endtime = 0; LinkBenchOp type = LinkBenchOp.UNKNOWN; // initialize to invalid value Link link = new Link(); try { if (r <= pc_addlink) { // generate add request type = LinkBenchOp.ADD_LINK; link.id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); link.link_type = id2chooser.chooseRandomLinkType(rng); link.id2 = id2chooser.chooseForOp(rng, link.id1, link.link_type, ID2Chooser.P_ADD_EXIST); link.visibility = LinkStore.VISIBILITY_DEFAULT; link.version = 0; link.time = System.currentTimeMillis(); link.data = linkAddDataGen.fill(rng, new byte[(int)linkDataSize.choose(rng)]); starttime = System.nanoTime(); // no inverses for now boolean alreadyExists = linkStore.addLink(dbid, link, true); boolean added = !alreadyExists; endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("addLink id1=" + link.id1 + " link_type=" + link.link_type + " id2=" + link.id2 + " added=" + added); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_deletelink) { type = LinkBenchOp.DELETE_LINK; long id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); long id2 = id2chooser.chooseForOp(rng, id1, link_type, ID2Chooser.P_DELETE_EXIST); starttime = System.nanoTime(); linkStore.deleteLink(dbid, id1, link_type, id2, true, // no inverse false); endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("deleteLink id1=" + id1 + " link_type=" + link_type + " id2=" + id2); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_updatelink) { type = LinkBenchOp.UPDATE_LINK; link.id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); link.link_type = id2chooser.chooseRandomLinkType(rng); // Update one of the existing links link.id2 = id2chooser.chooseForOp(rng, link.id1, link.link_type, ID2Chooser.P_UPDATE_EXIST); link.visibility = LinkStore.VISIBILITY_DEFAULT; link.version = 0; link.time = System.currentTimeMillis(); link.data = linkUpDataGen.fill(rng, new byte[(int)linkDataSize.choose(rng)]); starttime = System.nanoTime(); // no inverses for now boolean found1 = linkStore.addLink(dbid, link, true); boolean found = found1; endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("updateLink id1=" + link.id1 + " link_type=" + link.link_type + " id2=" + link.id2 + " found=" + found); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_countlink) { type = LinkBenchOp.COUNT_LINK; long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); starttime = System.nanoTime(); long count = linkStore.countLinks(dbid, id1, link_type); endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("countLink id1=" + id1 + " link_type=" + link_type + " count=" + count); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_getlink) { type = LinkBenchOp.MULTIGET_LINK; long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); int nid2s = 1; if (multigetDist != null) { nid2s = (int)multigetDist.choose(rng); } long id2s[] = id2chooser.chooseMultipleForOp(rng, id1, link_type, nid2s, ID2Chooser.P_GET_EXIST); starttime = System.nanoTime(); int found = getLink(id1, link_type, id2s); assert(found >= 0 && found <= nid2s); endtime = System.nanoTime(); if (found > 0) { numfound += found; } else { numnotfound += nid2s - found; } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_getlinklist) { type = LinkBenchOp.GET_LINKS_LIST; Link links[]; if (rng.nextDouble() < p_historical_getlinklist && !this.listTailHistory.isEmpty()) { // Get linklist tail is not counted?? links = getLinkListTail(); // System.err.println("getlinklist tail"); } else { long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); starttime = System.nanoTime(); links = getLinkList(id1, link_type); endtime = System.nanoTime(); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), links == null?1:0); // int count = ((links == null) ? 0 : links.length); if (recordStats && links != null) { // stats.addStats(LinkBenchOp.RANGE_SIZE, count, false); _measurements.measure("LinkRangeSize", links.length); } } else if (r <= pc_addnode) { type = LinkBenchOp.ADD_NODE; Node newNode = createAddNode(); starttime = System.nanoTime(); lastNodeId = nodeStore.addNode(dbid, newNode); endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("addNode " + newNode); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_updatenode) { type = LinkBenchOp.UPDATE_NODE; // Choose an id that has previously been created (but might have // been since deleted long upId = chooseRequestID(DistributionType.NODE_UPDATES, lastNodeId); // Generate new data randomly Node newNode = createUpdateNode(upId); starttime = System.nanoTime(); boolean changed = nodeStore.updateNode(dbid, newNode); endtime = System.nanoTime(); lastNodeId = upId; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("updateNode " + newNode + " changed=" + changed); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_deletenode) { type = LinkBenchOp.DELETE_NODE; long idToDelete = chooseRequestID(DistributionType.NODE_DELETES, lastNodeId); starttime = System.nanoTime(); boolean deleted = nodeStore.deleteNode(dbid, LinkStore.DEFAULT_NODE_TYPE, idToDelete); endtime = System.nanoTime(); lastNodeId = idToDelete; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("deleteNode " + idToDelete + " deleted=" + deleted); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_getnode) { type = LinkBenchOp.GET_NODE; starttime = System.nanoTime(); long idToFetch = chooseRequestID(DistributionType.NODE_READS, lastNodeId); Node fetched = nodeStore.getNode(dbid, LinkStore.DEFAULT_NODE_TYPE, idToFetch); endtime = System.nanoTime(); lastNodeId = idToFetch; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { if (fetched == null) { logger.trace("getNode " + idToFetch + " not found"); } else { logger.trace("getNode " + fetched); } } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_ali_login) { type = LinkBenchOp.ALI_LOGIN; // Choose an id that has previously been created (but might have // been since deleted long upId = chooseRequestID(DistributionType.NODE_UPDATES, lastNodeId); // Generate new data randomly // Node newNode = createUpdateNode(upId); starttime = System.nanoTime(); long updated_nodes = nodeStore.aliLogin(upId); endtime = System.nanoTime(); lastNodeId = upId; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("login " + upId + " updated_nodes=" + updated_nodes); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_ali_reg) { type = LinkBenchOp.ALI_REG; Node newNode = createAddNode(); newNode.id = _nodeid.getAndIncrement(); if (id2chooser.calcLinkCount(newNode.id, LinkBase.REFERRER_TYPE) == 1) { starttime = System.nanoTime(); long referrer_id = id2chooser.chooseForOp(rng, newNode.id, LinkBase.REFERRER_TYPE, 1); nodeStore.aliRegRef(newNode, referrer_id); endtime = System.nanoTime(); } else { starttime = System.nanoTime(); nodeStore.aliReg(newNode); endtime = System.nanoTime(); } lastNodeId = newNode.id; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("register " + newNode); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_ali_pay) { // generate add request type = LinkBenchOp.ALI_PAY; link.id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); link.id2 = id2chooser.chooseForOp(rng, link.id1, LinkBase.TRANSFER_FAKE_LINK_TYPE, ID2Chooser.P_UPDATE_EXIST); starttime = System.nanoTime(); // no inverses for now boolean alreadyExists = nodeStore.aliPay(link.id1, link.id2); boolean added = !alreadyExists; endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("ali pay id1=" + link.id1 + " id2=" + link.id2 + " added=" + added); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_ali_get_fan) { // taken from get link list type = LinkBenchOp.ALI_GET_FAN; Node nodes[]; long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); starttime = System.nanoTime(); nodes = linkStore.aliGetFan(id1); endtime = System.nanoTime(); _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), nodes == null?1:0); } else if (r <= pc_ali_get_follow) { // taken from get link list type = LinkBenchOp.ALI_GET_FOLLOW; Node nodes[]; long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); long link_type = id2chooser.chooseRandomLinkType(rng); starttime = System.nanoTime(); nodes = linkStore.aliGetFollow(id1); endtime = System.nanoTime(); _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), nodes == null?1:0); } else if (r <= pc_ali_recom) { // taken from get link list type = LinkBenchOp.ALI_RECOM; Node nodes[]; long id1 = chooseRequestID(DistributionType.LINK_READS, link.id1); starttime = System.nanoTime(); nodes = linkStore.aliRecom(id1); endtime = System.nanoTime(); _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), nodes == null?1:0); } else if (r <= pc_ali_follow) { // tabek from add link type = LinkBenchOp.ALI_FOLLOW; link.id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); link.link_type = LinkBase.LINKBENCH_DEFAULT_TYPE; link.id2 = id2chooser.chooseForOp(rng, link.id1, link.link_type, ID2Chooser.P_ADD_EXIST); link.time = System.currentTimeMillis(); starttime = System.nanoTime(); // no inverses for now boolean alreadyExists = linkStore.aliFollow(link); endtime = System.nanoTime(); _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else if (r <= pc_ali_unfollow) { // taken from delete link type = LinkBenchOp.ALI_UNFOLLOW; long id1 = chooseRequestID(DistributionType.LINK_WRITES, link.id1); long id2 = id2chooser.chooseForOp(rng, id1, LinkBase.LINKBENCH_DEFAULT_TYPE, ID2Chooser.P_DELETE_EXIST); starttime = System.nanoTime(); linkStore.deleteLink(dbid, id1, LinkBase.LINKBENCH_DEFAULT_TYPE, id2, true, // no inverse false); endtime = System.nanoTime(); if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("ali unfollow id1=" + id1 + " link_type=" + LinkBase.LINKBENCH_DEFAULT_TYPE + " id2=" + id2); } _measurements.measure(type.displayName(), (endtime - starttime)/1000); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 0); } else { logger.error("No-op in requester: last probability < 1.0"); return false; } // convert to microseconds long timetaken = (endtime - starttime)/1000; if (recordStats) { // record statistics stats.addStats(type, timetaken, false); latencyStats.recordLatency(requesterID, type, timetaken); } return true; } catch (ConflictException e) { long endtime2 = System.nanoTime(); long timetaken2 = (endtime2 - starttime)/1000; _measurements.measure(type.displayName(), timetaken2); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 1); if (recordStats) { stats.addStats(type, timetaken2, true); } linkStore.clearErrors(requesterID); return false; } catch (MissingException e) { long endtime2 = System.nanoTime(); long timetaken2 = (endtime2 - starttime)/1000; _measurements.measure(type.displayName(), timetaken2); _measurements.measure("OVERALL_M", (endtime - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 2); if (recordStats) { stats.addStats(type, timetaken2, true); } linkStore.clearErrors(requesterID); return false; } catch (Throwable e){//Catch exception if any long endtime2 = System.nanoTime(); long timetaken2 = (endtime2 - starttime)/1000; _measurements.measure(type.displayName(), timetaken2); _measurements.measure("OVERALL_M", (endtime2 - starttime)/1000); _measurements.reportReturnCode(type.displayName(), 3); logger.error(type.displayName() + " error " + e.getMessage(), e); if (recordStats) { stats.addStats(type, timetaken2, true); } linkStore.clearErrors(requesterID); System.exit(1); return false; } } /** * Create a new node for adding to database * @return */ private Node createAddNode() { byte data[] = nodeAddDataGen.fill(rng, new byte[(int)nodeDataSize.choose(rng)]); return new Node(-1, LinkStore.DEFAULT_NODE_TYPE, 1, (int)(System.currentTimeMillis()/1000), data); } /** * Create new node for updating in database */ private Node createUpdateNode(long id) { byte data[] = nodeUpDataGen.fill(rng, new byte[(int)nodeDataSize.choose(rng)]); return new Node(id, LinkStore.DEFAULT_NODE_TYPE, 2, (int)(System.currentTimeMillis()/1000), data); } @Override public void run() { logger.info("Requester thread #" + requesterID + " started: will do " + numRequests + " ops after " + warmupTime + " second warmup"); logger.debug("Requester thread #" + requesterID + " first random number " + rng.nextLong()); try { this.linkStore.initialize(props, Phase.REQUEST, requesterID); if (this.nodeStore != null && this.nodeStore != this.linkStore) { this.nodeStore.initialize(props, Phase.REQUEST, requesterID); } } catch (Exception e) { logger.error("Error while initializing store", e); throw new RuntimeException(e); } long warmupStartTime = System.currentTimeMillis(); boolean warmupDone = warmupTime <= 0; long benchmarkStartTime; if (!warmupDone) { benchmarkStartTime = warmupStartTime + warmupTime * 1000; } else { benchmarkStartTime = warmupStartTime; } long endTime = benchmarkStartTime + maxTime * 1000; long lastUpdate = warmupStartTime; long curTime = warmupStartTime; long i; if (singleAssoc) { LinkBenchOp type = LinkBenchOp.UNKNOWN; try { Link link = new Link(); // add a single assoc to the database link.id1 = 45; link.id1 = 46; type = LinkBenchOp.ADD_LINK; // no inverses for now linkStore.addLink(dbid, link, true); // read this assoc from the database over and over again type = LinkBenchOp.MULTIGET_LINK; for (i = 0; i < numRequests; i++) { int found = getLink(link.id1, link.link_type, new long[]{link.id2}); if (found == 1) { requestsDone++; } else { logger.warn("ThreadID = " + requesterID + " not found link for id1=45"); } } } catch (Throwable e) { logger.error(type.displayName() + "error " + e.getMessage(), e); aborted = true; } closeStores(); return; } long warmupRequests = 0; long requestsSinceLastUpdate = 0; long lastStatDisplay_ms = curTime; long reqTime_ns = System.nanoTime(); double requestrate_ns = ((double)requestrate)/1e9; // long start_time = System.currentTimeMillis(); while (true) { if (use_duration) { long sec = (System.currentTimeMillis() - start_time) / 1000L; if (sec >= duration) break; } else if (requestsDone < numRequests) { break; } if (requestrate > 0) { reqTime_ns = Timer.waitExpInterval(rng, reqTime_ns, requestrate_ns); } boolean success = oneRequest(warmupDone); if (!success) { errors++; if (maxFailedRequests >= 0 && errors > maxFailedRequests) { logger.error(String.format("Requester #%d aborting: %d failed requests" + " (out of %d total) ", requesterID, errors, requestsDone)); aborted = true; break; } } curTime = System.currentTimeMillis(); // Track requests done if (warmupDone) { requestsDone++; requestsSinceLastUpdate++; if (requestsSinceLastUpdate >= RequestProgress.THREAD_REPORT_INTERVAL) { progressTracker.addRetries(linkStore.getRetries()); progressTracker.update(requestsSinceLastUpdate); requestsSinceLastUpdate = 0; } } else { warmupRequests++; } // Per-thread periodic progress updates if (curTime > lastUpdate + progressFreq_ms) { if (warmupDone) { logger.info(String.format("Requester #%d %d/%d requests done", requesterID, requestsDone, numRequests)); lastUpdate = curTime; } else { logger.info(String.format("Requester #%d warming up. " + " %d warmup requests done. %d/%d seconds of warmup done", requesterID, warmupRequests, (curTime - warmupStartTime) / 1000, warmupTime)); lastUpdate = curTime; } } // Per-thread periodic stat dumps after warmup done if (warmupDone && (lastStatDisplay_ms + displayFreq_ms) <= curTime) { displayStats(lastStatDisplay_ms, curTime); stats.resetSamples(); lastStatDisplay_ms = curTime; } // Check if warmup completed if (!warmupDone && curTime >= benchmarkStartTime) { warmupDone = true; lastUpdate = curTime; lastStatDisplay_ms = curTime; requestsSinceLastUpdate = 0; logger.info(String.format("Requester #%d warmup finished " + " after %d warmup requests. 0/%d requests done", requesterID, warmupRequests, numRequests)); lastUpdate = curTime; } // Enforce time limit if (curTime > endTime) { logger.info(String.format("Requester #%d: time limit of %ds elapsed" + ", shutting down.", requesterID, maxTime)); break; } } // Do final update of statistics progressTracker.update(requestsSinceLastUpdate); // displayStats(lastStatDisplay_ms, System.currentTimeMillis()); // Report final stats logger.info("ThreadID = " + requesterID + " total requests = " + requestsDone + " requests/second = " + ((1000 * requestsDone)/ Math.max(1, (curTime - benchmarkStartTime))) + " found = " + numfound + " not found = " + numnotfound + " history queries = " + numHistoryQueries + "/" + stats.getCount(LinkBenchOp.GET_LINKS_LIST)); closeStores(); } /** * Close datastores before finishing */ private void closeStores() { linkStore.close(); if (nodeStore != null && nodeStore != linkStore) { nodeStore.close(); } } private void displayStats(long lastStatDisplay_ms, long now_ms) { stats.displayStats(lastStatDisplay_ms, now_ms, Arrays.asList( LinkBenchOp.MULTIGET_LINK, LinkBenchOp.GET_LINKS_LIST, LinkBenchOp.COUNT_LINK, LinkBenchOp.UPDATE_LINK, LinkBenchOp.ADD_LINK, LinkBenchOp.RANGE_SIZE, LinkBenchOp.ADD_NODE, LinkBenchOp.UPDATE_NODE, LinkBenchOp.DELETE_NODE, LinkBenchOp.GET_NODE)); } int getLink(long id1, long link_type, long id2s[]) throws Exception { Link links[] = linkStore.multigetLinks(dbid, id1, link_type, id2s); return links == null ? 0 : links.length; } Link[] getLinkList(long id1, long link_type) throws Exception { Link links[] = linkStore.getLinkList(dbid, id1, link_type); if (links == null) {return null;} if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("getLinkList(id1=" + id1 + ", link_type=" + link_type + ") => count=" + (links == null ? 0 : links.length)); } // If there were more links than limit, record if (links != null && links.length >= linkStore.getRangeLimit()) { Link lastLink = links[links.length-1]; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("Maybe more history for (" + id1 +"," + link_type + " older than " + lastLink.time); } addTailCacheEntry(lastLink); } return links; } Link[] getLinkListTail() throws Exception { assert(!listTailHistoryIndex.isEmpty()); assert(!listTailHistory.isEmpty()); int choice = rng.nextInt(listTailHistory.size()); Link prevLast = listTailHistory.get(choice); // Get links past the oldest last retrieved Link links[] = linkStore.getLinkList(dbid, prevLast.id1, prevLast.link_type, 0, prevLast.time, 1, linkStore.getRangeLimit()); if (links == null) {return null;} if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("getLinkListTail(id1=" + prevLast.id1 + ", link_type=" + prevLast.link_type + ", max_time=" + prevLast.time + " => count=" + (links == null ? 0 : links.length)); } if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("Historical range query for (" + prevLast.id1 +"," + prevLast.link_type + " older than " + prevLast.time + ": " + (links == null ? 0 : links.length) + " results"); } if (links != null && links.length == linkStore.getRangeLimit()) { // There might be yet more history Link last = links[links.length-1]; if (Level.TRACE.isGreaterOrEqual(debuglevel)) { logger.trace("might be yet more history for (" + last.id1 +"," + last.link_type + " older than " + last.time); } // Update in place listTailHistory.set(choice, last.clone()); } else { // No more history after this, remove from cache removeTailCacheEntry(choice, null); } numHistoryQueries++; return links; } /** * Add a new link to the history cache, unless already present * @param lastLink the last (i.e. lowest timestamp) link retrieved */ private void addTailCacheEntry(Link lastLink) { HistoryKey key = new HistoryKey(lastLink); if (listTailHistoryIndex.containsKey(key)) { // Already present return; } if (listTailHistory.size() < listTailHistoryLimit) { listTailHistory.add(lastLink.clone()); listTailHistoryIndex.put(key, listTailHistory.size() - 1); } else { // Need to evict entry int choice = rng.nextInt(listTailHistory.size()); removeTailCacheEntry(choice, lastLink.clone()); } } /** * Remove or replace entry in listTailHistory and update index * @param pos index of entry in listTailHistory * @param repl replace with this if not null */ private void removeTailCacheEntry(int pos, Link repl) { Link entry = listTailHistory.get(pos); if (pos == listTailHistory.size() - 1) { // removing from last position, don't need to fill gap listTailHistoryIndex.remove(new HistoryKey(entry)); int lastIx = listTailHistory.size() - 1; if (repl == null) { listTailHistory.remove(lastIx); } else { listTailHistory.set(lastIx, repl); listTailHistoryIndex.put(new HistoryKey(repl), lastIx); } } else { if (repl == null) { // Replace with last entry in cache to fill gap repl = listTailHistory.get(listTailHistory.size() - 1); listTailHistory.remove(listTailHistory.size() - 1); } listTailHistory.set(pos, repl); listTailHistoryIndex.put(new HistoryKey(repl), pos); } } public static class RequestProgress { // How many ops before a thread should register its progress static final int THREAD_REPORT_INTERVAL = 250; /** How many ops before a progress update should be printed to console */ private final long interval; private final Logger progressLogger; private long totalRequests; private final AtomicLong requestsDone; private final AtomicInteger retries; private long benchmarkStartTime; private long last_update_time; private long last_update_done; private long warmupTime_s; private long timeLimit_s; private boolean use_duration = false; private int duration = 0; public RequestProgress(Logger progressLogger, long totalRequests, long timeLimit_s, long warmupTime_s, long interval) { this.interval = interval; this.progressLogger = progressLogger; this.totalRequests = totalRequests; this.requestsDone = new AtomicLong(); this.retries = new AtomicInteger(); this.timeLimit_s = timeLimit_s; this.warmupTime_s = warmupTime_s; this.last_update_done = 0; } public void setUseDuration(int d) { use_duration = true; duration = d; } public void startTimer() { benchmarkStartTime = System.currentTimeMillis() + warmupTime_s * 1000; last_update_time = benchmarkStartTime; LinkBenchRequest.start_time = benchmarkStartTime; } public long getBenchmarkStartTime() { return benchmarkStartTime; } public void addRetries(int retry) { retries.addAndGet(retry); } public void update(long requestIncr) { long curr = requestsDone.addAndGet(requestIncr); long prev = curr - requestIncr; if ((curr / interval) > (prev / interval) || curr == totalRequests) { float progressPercent = ((float) curr) / totalRequests * 100; long now = System.currentTimeMillis(); long elapsed = now - benchmarkStartTime; float elapsed_s = ((float) elapsed) / 1000; float limitPercent = (elapsed_s / ((float) timeLimit_s)) * 100; float rate = curr / ((float)elapsed_s); if (use_duration) { float slot_sec = (now - last_update_time)/(float)1000; float latest_tp = (curr - last_update_done)/(float)slot_sec; System.err.println(String.format( "%.1f/%d duration, %d done, total tp: %.1f ops/sec; tp of last %.1fs: %.1f ops/sec, aborts is %d", elapsed_s, duration, curr, rate, slot_sec, latest_tp, retries.get())); } else { System.err.println(String.format( "%d/%d requests finished: %.1f%% complete at %.1f ops/sec; tp of last 1s: %.1f ops/sec" + " %.1f/%d secs elapsed: %.1f%% of time limit used", curr, totalRequests, progressPercent, rate, (curr - last_update_done)/((now - last_update_time)/1000.0), elapsed_s, timeLimit_s, limitPercent)); } last_update_time = now; last_update_done = curr; } } public void force_print() { long curr = requestsDone.get(); float progressPercent = ((float) curr) / totalRequests * 100; long now = System.currentTimeMillis(); long elapsed = now - benchmarkStartTime; float elapsed_s = ((float) elapsed) / 1000; float limitPercent = (elapsed_s / ((float) timeLimit_s)) * 100; float rate = curr / ((float)elapsed_s); if (use_duration) { float slot_sec = (now - last_update_time)/(float)1000; float latest_tp = (curr - last_update_done)/(float)slot_sec; System.err.println(String.format( "%.1f/%d duration, %d done, total tp: %.1f ops/sec; tp of last %.1fs: %.1f ops/sec, aborts is %d", elapsed_s, duration, curr, rate, slot_sec, latest_tp, retries.get())); } else { System.err.println(String.format( "%d/%d requests finished: %.1f%% complete at %.1f ops/sec; tp of last 1s: %.1f ops/sec" + " %.1f/%d secs elapsed: %.1f%% of time limit used", curr, totalRequests, progressPercent, rate, (curr - last_update_done)/((now - last_update_time)/1000.0), elapsed_s, timeLimit_s, limitPercent)); } last_update_time = now; last_update_done = curr; } } public static RequestProgress createProgress(Logger logger, Properties props) { long total_requests = ConfigUtil.getLong(props, Config.NUM_REQUESTS) * ConfigUtil.getLong(props, Config.NUM_REQUESTERS); long progressInterval = ConfigUtil.getLong(props, Config.REQ_PROG_INTERVAL, 10000L); long warmupTime = ConfigUtil.getLong(props, Config.WARMUP_TIME, 0L); long maxTime = ConfigUtil.getLong(props, Config.MAX_TIME); boolean use_duration = ConfigUtil.getBool(props, Config.USE_DURATION, true); int duration = ConfigUtil.getInt(props, Config.DURATION, 0); RequestProgress rp = new RequestProgress(logger, total_requests, maxTime, warmupTime, progressInterval); if (use_duration) { rp.setUseDuration(duration); } return rp; } }
1.460938
1
src/gmail/auto/send/data.java
davisnguyen111195/Auto1
1
73
package gmail.auto.send; import java.util.List; public class data { public static List<data> listData; public static List<String> listTemplate; public static List<String> listSubject; public static List<String> listEmail; private String user; private String pass; private String recoveryMail; public data() { } public data(String user, String pass, String recoveryMail) { this.user = user; this.pass = pass; this.recoveryMail = recoveryMail; } @Override public String toString() { return user + "," + pass + "," + recoveryMail; } public void setUser(String user) { this.user = user; } public void setPass(String pass) { this.pass = pass; } public void setRecoveryMail(String recoveryMail) { this.recoveryMail = recoveryMail; } public String getUser() { return user; } public String getPass() { return pass; } public String getRecoveryMail() { return recoveryMail; } }
1.28125
1
src/main/java/com/ruoyi/project/system/kbm/service/ITOrgService.java
lzsyt/ruoyi_kbm
0
81
package com.ruoyi.project.system.kbm.service; import com.ruoyi.project.system.kbm.domain.TOrg; import java.util.List; /** * 【请填写功能名称】Service接口 * * @author ruoyi * @date 2019-09-19 */ public interface ITOrgService { public List<TOrg> getChild(List<TOrg> orgs); /** * 查询【请填写功能名称】 * * @param id 【请填写功能名称】ID * @return 【请填写功能名称】 */ public TOrg selectTOrgById(String id); /** * 查询【请填写功能名称】列表 * * @param tOrg 【请填写功能名称】 * @return 【请填写功能名称】集合 */ public List<TOrg> selectTOrgList(TOrg tOrg); /** * 新增【请填写功能名称】 * * @param tOrg 【请填写功能名称】 * @return 结果 */ public int insertTOrg(TOrg tOrg); /** * 修改【请填写功能名称】 * * @param tOrg 【请填写功能名称】 * @return 结果 */ public int updateTOrg(TOrg tOrg); /** * 批量删除【请填写功能名称】 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteTOrgByIds(String ids); /** * 删除【请填写功能名称】信息 * * @param id 【请填写功能名称】ID * @return 结果 */ public int deleteTOrgById(String id); }
1.273438
1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
1,543
Edit dataset card